Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty ClassName

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?

like image 490
Fijir Avatar asked Apr 07 '16 22:04

Fijir


People also ask

Can we give className to fragment?

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.

How do you add a class name based on condition in react?

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.


1 Answers

You can return null instead of the empty string:

return (
   <div className={this.state.foo ? 'active' : null }></div>
)
like image 121
Florian Cargoet Avatar answered Oct 03 '22 14:10

Florian Cargoet