Empty class name

I have an 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- falsein the browser, my code will look:

<div class></div>

Is it possible to add an attribute classif it is empty?

+6
source share
2 answers

You could probably do

var props = {};
if (this.state.foo) {
  props.myClass = 'active';
}
return (
   <div {...props}></div>
);
+4
source

You can return null instead of an empty string:

return (
   <div className={this.state.foo ? 'active' : null }></div>
)
+7
source

All Articles