Katie7
Katie7

Reputation: 879

How do you conditionally apply multiple classes to a single Material UI classes prop

I am using the Material UI Drawer and would like to apply a class called "paperStyle" to the classes prop with the rule name "paper" and then conditionally apply an additional class called "specialPaperStyle" if the user is of a particular type. But I haven't been able to apply two classes to the paper rule, let alone apply it conditionally and wondered if anyone knew what to do?

Here are the key parts of my code:

Styles

const useStyles = makeStyles(theme => ({
  paperStyle: {
    width: drawerWidth,
    boxShadow: 'inset 0 0.3rem 1.5rem rgba(0,0,0,0.19)',
    color: theme.palette.primary.main,
    [theme.breakpoints.up('lg')]: {
      minHeight: '100%',
      position: 'relative',
    }, 
  },
  specialPaperStyle:{ 
    backgroundImage: 'linear-gradient(to bottom right, #27133f, transparent)',
},
}));

Material UI drawer

<Drawer
   classes={{
     paper: classes.paper,
   }}
 >
      Contents of drawer
</Drawer>

The above works in that my paperStyle class is being applied, but how do I conditionally apply the specialPaperStyle class to paper? For example:

Doesn't work!

<Drawer
   classes={{
     paper: {`${classes.paperStyle isSpecial && $classes.specialPaperStyle}`},
   }}
 >
      Contents of drawer
</Drawer>

Many thanks,

Katie

Upvotes: 1

Views: 1702

Answers (2)

buzatto
buzatto

Reputation: 10382

material-ui comes with a handy package clsx that makes easier to add classes based on specific conditions. You can pass several class arguments, or also objects that will display the class key if the given value is truthy:

import clsx from 'clsx';

<Drawer
   classes={{
     paper: {clsx(classes.paperStyle, {[classes.specialPaperStyle]: isSpecial})},
   }}
 >
      Contents of drawer
</Drawer>

docs about clsx on material-ui

Upvotes: 2

Kirill Skomarovskiy
Kirill Skomarovskiy

Reputation: 1565

How about this?

UPDATED

<Drawer
   classes={{
     paper: {`${classes.paperStyle} ${isSpecial ? classes.specialPaperStyle : ''}`},
   }}
 >
      Contents of drawer
</Drawer>

Upvotes: 1

Related Questions