How to dynamically add a class to manual class names? How to dynamically add a class to manual class names? reactjs reactjs

How to dynamically add a class to manual class names?


You can either do this, normal JavaScript:

className={'wrapper searchDiv ' + this.state.something}

or the string template version, with backticks:

className={`wrapper searchDiv ${this.state.something}`}

Both types are of course just JavaScript, but the first pattern is the traditional kind.

Anyway, in JSX, anything enclosed in curly brackets is executed as JavaScript, so you can basically do whatever you want there. But combining JSX strings and curly brackets is a no-go for attributes.


Depending on how many dynamic classes you need to add as your project grows it's probably worth checking out the classnames utility by JedWatson on GitHub. It allows you to represent your conditional classes as an object and returns those that evaluate to true.

So as an example from its React documentation:

render () {var btnClass = classNames({  'btn': true,  'btn-pressed': this.state.isPressed,  'btn-over': !this.state.isPressed && this.state.isHovered});return <button className={btnClass}>I'm a button!</button>;} 

Since React triggers a re-render when there is a state change, your dynamic class names are handled naturally and kept up to date with the state of your component.


A simple possible syntax will be:

<div className={`wrapper searchDiv ${this.state.something}`}>