Close Persistent Material UI Drawer on clicking outside
You can use the ClickAwayListener
component for this.
https://material-ui.com/api/click-away-listener/
import ClickAwayListener from '@material-ui/core/ClickAwayListener';
const drawer = (
<ClickAwayListener onClickAway={this.handleDrawerClose}>
<Drawer
variant="persistent"
anchor={anchor}
open={open}
classes={{
paper: classes.drawerPaper
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={this.handleDrawerClose}>
{theme.direction === "rtl" ? (
<ChevronRightIcon />
) : (
<ChevronLeftIcon />
)}
</IconButton>
</div>
<Divider />
<List>a asdasd</List>
<Divider />
<List>asdasd</List>
</Drawer>
</ClickAwayListener>
);
https://codesandbox.io/s/072ny1rjw
For the sake of searchers landing on this question. If you are having trouble with ClickAwayListener
and are not using variant='persistent'
. Try this instead: Providing a toggle function to ModalProps
onBackdropClick
<Drawer
open={drawerIsOpen}
ModalProps={{ onBackdropClick: this.toggleDrawer }}
>
<MenuItem>drawer item 1</MenuItem>
</Drawer>
I spend some time training to fix this, but I found a really a useful solution and is to change the variant to Temporary and use de onEscapeKeyDown and the onBackdropClick as follow:
<Drawer
variant="temporary"
onEscapeKeyDown={handleDrawerClose}
onBackdropClick={handleDrawerClose}
open={open}
...rest of your code...