timbo
timbo

Reputation: 14324

Add Cancel Icon for close of Material-UI Drawer

I'm using an IconButton with an onClick attribute to capture the event to close a persistent right-hand side Drawer. It all works perfectly as:

const styles = {
  list: {
    width: 250,
  },
  fullList: {
    width: 'auto',
  },
  close: {
    margin: 10,
    opacity: 0.7,
  }
};

class ContextDrawer extends Component {

  render() {
    const { classes } = this.props;

    const sideList = (
      <div className={classes.list}>
        <CheckedList />
      </div>
    );

    return (
      <div>
        <Drawer
          variant="persistent"
          anchor="right"
          open={this.props.open}
        >
          <div
            tabIndex={0}
            role="button"
          >
          <IconButton onClick={this.props.closeContextDrawer}>
            <CancelIcon className={classes.close} />
          </IconButton>
            {sideList}
          </div>
        </Drawer>
      </div>
    );
  }
}

export default withStyles(styles)(ContextDrawer);

```

which gives me this:

enter image description here

However, a style={{ float: 'right' }} on the IconButton results in a click on the icon no longer causing the action and instead a red outline of the top part of the Drawer:

enter image description here

Is there a better way to show an icon for a Drawer close?

Upvotes: 3

Views: 8828

Answers (1)

timbo
timbo

Reputation: 14324

With the IconButton wrapped in a DialogTitle and with a specific class on the DialogTitle, I have a workable solution:

  <Drawer
    variant="persistent"
    anchor="right"
    open={this.props.open}
  >
  <DialogTitle disableTypography className="drawerTitle">
    <IconButton onClick={this.props.closeContextDrawer}>
        <CancelIcon />
    </IconButton>
  </DialogTitle>
    {sideList}
  </Drawer>

and css is:

.drawerTitle {
  display: flex;
  justify-content: flex-end;
  padding: 0 !important;
}

produces:

enter image description here

Update

There's a nicer and cleaner way to do this, at least for left-side and right-side Drawers. You can use:

  <div className={classes.drawerHeader}>
    <IconButton onClick={closeDrawer}>
      <ChevronLeftIcon />
    </IconButton>
  </div>
  </Divider>

which will give you this:

enter image description here

The CSS I've used for the header is:

const styles = theme => ({
  drawerHeader: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: '0 8px',
    ...theme.mixins.toolbar,
  },
  ..

as bringing in the default mixins will set the drawer header to the same height as the toolbar at the appropriate breakpoints.

Upvotes: 6

Related Questions