javascript – How to add multiple classes to a ReactJS Component?

javascript – How to add multiple classes to a ReactJS Component?

I use ES6 template literals. For example:

const error = this.state.valid ?  : error
const classes = `form-control round-lg ${error}`

And then just render it:

<input className={classes} />

One-liner version:

<input className={`form-control round-lg ${this.state.valid ?  : error}`} />

I use classnames when there is a fair amount of logic required for deciding the classes to (not) use. An overly simple example:

...
    var liClasses = classNames({
      main-class: true,
      activeClass: self.state.focused === index
    });

    return (<li className={liClasses}>{data.name}</li>);
...

That said, if you dont want to include a dependency then there are better answers below.

javascript – How to add multiple classes to a ReactJS Component?

Just use JavaScript.

<li className={[activeClass, data.klass, main-class].join( )} />

If you want to add classes based keys and values in an object you can use the following:

function classNames(classes) {
  return Object.entries(classes)
    .filter(([key, value]) => value)
    .map(([key, value]) => key)
    .join( );
}

const classes = {
  maybeClass: true,
  otherClass: true,
  probablyNotClass: false,
};

const myClassNames = classNames(classes);
// Output: maybeClass otherClass

<li className={myClassNames} />

Or even simpler:

const isEnabled = true;
const isChecked = false;

<li className={[isEnabled && enabled, isChecked && checked]
  .filter(e => !!e)
  .join( )
} />
// Output:
// <li className={enabled} />

Leave a Reply

Your email address will not be published.