I’m using Material UI with React, I have a div:

<div className={classes.div}></div>

I want to add a conditional class to it:

<div className={classes.div + divActive ? `${classes.div}__active` : ''}></div>

The second example does not work – it always returns <div class="makeStyles-div-2__active"></div> where it should be:

divActive false: <div class="makeStyles-div-2"></div>

divActive true: <div class="makeStyles-div-2 makeStyles-div-2__active"></div>

What am I missing? I tried wrapping classes.div in extra template literal like:

<div className={`${classes.div}` + divActive ? `${classes.div}__active` : ''}></div>

But same results. When I remove the first class (classes.div) the divActive switch if seems to be working and toggles between active/inactive, so I guess my issue lies in the first variable, but what’s wrong with it?


Wrap the ternary condition in parenthesis & add some whitespace when divActive returns true

<div className={classes.div + (divActive ? ` ${classes.div}__active` : '')}></div>

Write a comment

Your email address will not be published. Required fields are marked *