There have been many questions on StackOverflow relating to applying conditional classnames to React components; however, I have not seen a good answer for this particular situation:
I have a basic div that I want to conditionally apply the "is-required" class. Here is my approach:
<div className={`some-class ${isRequired && 'is-required'}`}>
The main issue here is that when isRequired is false, then my compiled HTML code ends up looking like this:
<div class='some-class false'>
Obviously, I could use a ternary operator like this so I can return an empty string instead:
<div className={`some-class ${isRequired ? 'is-required' : ''}`}>
But then in the compiled HTML code there is this extra random space included in the class, which won't cause any rendering issues, but I still don't like it:
<div class='some-class '>
Even still, I could remove the space after "someClass" and include it before "isRequired", but now it's harder to read and feels kind of clunky:
<div className={`some-class${isRequired ? ' is-required' : ''}`}>
I have heard of utilities such as classnames, but I am looking for a simple solution where I don't need any additional packages.
What is the recommended approach here?
Actually, there are many ways to do that, here's one of them.
<div className={isRequired ? 'some-class is-required': 'some-class'}>
or you can return null
<div className={isRequired ? 'is-required' : null}>
In order, if you have several classes.
<div className={isRequired ? 'some-class is-required': isDisabled ? 'some-disabled-class' : 'some-class'}>
https://reactjs.org/docs/conditional-rendering.html
class App extends React.Component {
constructor() {
super();
this.state = {
isRequired: false
};
}
render() {
return (
<div className="App">
<div className={this.state.isRequired ? 'is-required' : null}>Null</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>