I’m not a React expert but I’ve worked with the framework in the past and I have to say that classnames is something that helps you a lot.
Code is better than words. So, I used to do something like this
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MyComponent = ({ condition }) => ( | |
<div className={`myClass ${condition ? 'is-active' : ''}`}></div> | |
) |
or…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MyComponent = ({ condition }) => { | |
const myComponentClass = condition ? 'is-active' : ''; | |
return ( | |
<div className={`myClass ${myComponentClass}`}></div> | |
) | |
} |
It works… but thinking about the possibility of the number of CSS classes start to increase, this approach wouldn’t be good enough. So, I found out this magic called classnames.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import classnames from 'classnames'; | |
const MyComponent = ({ condition, anotherCondition }) => { | |
const myComponentClasses = classNames({ | |
'myClass': true, | |
'is-active': condition, | |
'has-icon': anotherCondition | |
}); | |
return ( | |
<div className={myComponentClasses}></div> | |
) | |
} |