Manage Modal Visibility with MaterialUI’s ClickAwayListener
Posted 2021-03-02
tl;dr In MaterialUI use
ClickAwayListener
to detect when a user clicks outside of your component.
Something important about components that pop up on a user action is detecting when someone clicks outside of them so you can stop showing it. Anytime I’ve done this by hand it usually involves making some background container with some less than simple styles that takes up the entire page, is transparent to the user, and registers an on-click callback which handles the component’s visibility.
<div className="modal-background" onClick={() => setShowing(false)}>
{showing && <div>The rest of the owl</div>}
</div>
This is not only annoying, but something you don’t have to do when you’re using MaterialUI. The ClickAwayListener
can arbitrarily wrap a component to manage when a user clicks outside of it.
<ClickAwayListener onClickAway={handleClickAway}>
{showing && <div>The rest of the owl</div>}
</ClickAwayListener>
The full documentation can be found here.