I have example:
var myClass = '';
if (this.state.foo) myClass = 'active';
return (
<div className={myClass}></div>
)
Or inside return
:
return (
<div className={this.state.foo ? 'active' : '' }></div>
)
If this.state.foo
is false
in browser my code will look:
<div class></div>
Is it possible do not add class
attribute if it's empty?
If you want a className, this className will have to apply to an element, no ? And Fragments do not render any element, so you can't use a className with it.
One of the best ways is to use the prop to set a different class name inside the component. Then you can write some CSS that will display the component differently when that class is applied.
You can return null instead of the empty string:
return (
<div className={this.state.foo ? 'active' : null }></div>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With