[css] How to dynamically add a class to manual class names?

I need to add a dynamic class to a list of regular classes, but have no idea how (I'm using babel), something like this:

<div className="wrapper searchDiv {this.state.something}">
...
</div>

Any ideas?

This question is related to css reactjs

The answer is


If you need style names which should appear according to the state condition, I prefer to use this construction:

<div className={'wrapper searchDiv' + (this.state.something === "a" ? " anotherClass" : "")'}>

If you're using css modules this is what worked for me.

const [condition, setCondition] = useState(false);

\\ toggle condition

return (
  <span className={`${styles.always} ${(condition ? styles.sometimes : '')`}>
  </span>
)

const ClassToggleFC= () =>{
  
  const [isClass, setClass] = useState(false);

  const toggle =() => {
       setClass( prevState => !prevState)
  }
  
  return(
      <>
        <h1 className={ isClass ? "heading" : ""}> Hiii There </h1>
       <button onClick={toggle}>Toggle</button>
      </>
   )

}

I simply created a Function Component. Inside I take a state and set initial value is false..

I have a button for toggling state..

Whenever we change state rerender component and if state value (isClass) is false h1's className should be "" and if state value (isClass) is true h1's className is "heading"


Here is the Best Option for Dynamic className , just do some concatenation like we do in Javascript.

     className={
        "badge " +
        (this.state.value ? "badge-primary " : "badge-danger ") +
        " m-4"
      }

try this using hooks:

const [dynamicClasses, setDynamicClasses] = React.useState([
    "dynamicClass1", "dynamicClass2"
]);

and add this in className attribute :

<div className=`wrapper searchDiv ${[...dynamicClasses]}`>
...
</div>

to add class :

    const addClass = newClass => {
       setDynamicClasses([...dynamicClasses, newClass])
    }

to delete class :

        const deleteClass= classToDelete => {

           setDynamicClasses(dynamicClasses.filter(class = > {
             class !== classToDelete
           }));

        }

getBadgeClasses() {
    let classes = "badge m-2 ";
    classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
    return classes;
}

<span className={this.getBadgeClasses()}>Total Count</span>

A simple possible syntax will be:

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

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.


className={css(styles.mainDiv, 'subContainer')}

This solution is tried and tested in React SPFx.

Also add import statement :

import { css } from 'office-ui-fabric-react/lib/Utilities';

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.


You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], { 
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />