689

I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on each li:

<li key={index} className={activeClass, data.class, "main-class"}></li>

My React component is:

var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help &amp; Support &nbsp; <span class='font-awesome icon-support'></span>(888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (
      <div className="acc-header-wrapper clearfix">
        <ul className="acc-btns-container">
          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (
              <li
                key={index}
                className={activeClass}
                onClick={self.clicked.bind(self, index)}
              >
                <a href="#" className={data.icon}>
                  {data.name}
                </a>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));
6

40 Answers 40

656

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'}`} />
6
  • This results in <input class=" form-control input-lg round-lg" />. Do note the extra space in beginning. This is valid, but ugly. Even react FAQ recommends another way or using the classnames package: reactjs.org/docs/faq-styling.html
    – Nakedible
    Commented Oct 20, 2018 at 16:22
  • 5
    This is the correct answer. Using a dependency for this as suggested in the "correct" answer is overkill. Commented Oct 4, 2019 at 17:50
  • 2
    I always love this answer but don't like that extra space in the end in case of falsy values. You can easily avoid then with trim(). Commented Oct 22, 2020 at 22:49
  • And if you're worried about having too many classes and a long template string, well, go on and break it in many lines, then use replace: `button ${true ? "style-2" : ""} ${false ? "disabled" : ""} `.trim().replace('\n', ' ') Commented Oct 22, 2020 at 22:59
  • 6
    @CodyMoniz and this answer guided me in the right direction! I had a situation where I needed to add multiple "variable" classes. className={ `${ props.variable } ${ props.variabletwo }` } worked! hours of not knowing how to search for this, remedied by this answer. Commented Jan 8, 2021 at 22:33
312

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 don't want to include a dependency then there are better answers below.

11
  • 383
    That's too bad you had to bring in a library of classnames just to add two classes to an element :(
    – user959690
    Commented Apr 10, 2018 at 22:37
  • 28
    @user959690 This is an example. This library is very nice when you're doing these things a lot and you have complex logic on when classes need to be applied or not. If you're doing something simple then sure just use templates, but every case is different and the reader should pick the right tool for their job.
    – Jack
    Commented Apr 11, 2018 at 17:06
  • 20
    @user959690 It's worth noting that it is now installed by NPM when using Webpack, so import classNames from 'classnames' then to use in a component className={classNames(classes.myFirstClass, classes.mySecondClass)} . Commented Jun 8, 2018 at 19:39
  • 6
    No need to use an external library, see my answer below.
    – Huw Davies
    Commented Aug 9, 2018 at 3:17
  • 3
    Library has other advantages : var btnClass = classNames({ btn: true, 'btn-pressed': this.state.isPressed, 'btn-over': !this.state.isPressed && this.state.isHovered }); return <button className={btnClass}>{this.props.label}</button>;
    – AmitJS94
    Commented Nov 5, 2019 at 8:29
280

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'} />
4
  • Here is the line that worked for me: className={['terra-Table', medOrder.resource.status]} Commented Jan 24, 2018 at 22:09
  • 4
    @DougWilhelm I don't think that works. It implicitly calls toString and creates a comma separated list of classes. github.com/facebook/react/issues/3138
    – 0xcaff
    Commented Jan 25, 2018 at 2:01
  • 12
    Good idea to use className={[listOfClasses].join(' ')} it's working for me thanks! Commented Oct 8, 2018 at 12:40
  • 4
    I prefer even more sexier version of className={[activeClass, data.klass, "main-class"].filter(Boolean).join(' ')} Commented Mar 22, 2021 at 15:10
202

Concat

No need to be fancy I am using CSS modules and it's easy

import style from '/css/style.css';

<div className={style.style1+ ' ' + style.style2} />

This will result in:

<div class="src-client-css-pages-style1-selectionItem src-client-css-pages-style2">

In other words, both styles

Conditionals

It would be easy to use the same idea with if's

const class1 = doIHaveSomething ? style.style1 : 'backupClass';

<div className={class1 + ' ' + style.style2} />

ES6

For the last year or so I have been using the template literals, so I feel its worth mentioning, i find it very expressive and easy to read:

`${class1} anotherClass ${class1}`
5
  • 2
    This worked for me, along with '-' names, ie: <nav className={styles.navbar + " " + styles['navbar-default']}>
    – Flinkman
    Commented Sep 9, 2016 at 13:38
  • 1
    LOL, i crack my head and the answer is simple concat :D. Btw this alsow work with CSS Loader Module
    – GusDeCooL
    Commented May 8, 2017 at 7:54
  • The problem with that is that you can't have optional classes (if undefined, then it will not be added), so it depends wither you are sure your class is not null (not optional). In case of optional there isn't better then a helper like classes(). we can use a ternary with templates like that className={slider${className? ` ${className}: ''}}``. But it's a lot. [note: 'something '+undefined = 'something underfined'. Js dynamic conversion. Commented Nov 2, 2018 at 15:59
  • 2
    Sure you can, just declare a variable above and use it conditionally :) Commented Mar 3, 2019 at 0:06
  • Forgot everything is actually just JavaScript and never tried this. Thanks, was a great help.
    – Wylie
    Commented Aug 26, 2021 at 9:34
113

This can be achieved with ES6 template literals:

<input className={`base-input-class ${class1} ${class2}`}>

(edited for clarity)

3
  • 9
    this almost worked for me I just had to interpolate the class1 too and no more errors, so it looks like this <input className={`${class1} ${class2}`}> Commented Aug 19, 2019 at 9:53
  • So if class1 does not exist, you end up with that large white space in the middle. Commented Dec 16, 2020 at 18:47
  • Yes, this would end up with whitespace. If you don't want whitespace you can use: <input className={['base-input-class', class1, class2].filter(x => x).join(' ')} />
    – Cody Moniz
    Commented Dec 17, 2020 at 20:20
51

You can create an element with multiple class names like this:

<li className="class1 class2 class3">foo</li>

Naturally, you can use a string containing the class names and manipulate this string to update the class names of the element.

var myClassNammes = 'class1 class2 class3';
...
<li className={myClassNames}>foo</li>
2
  • 1
    Did you test this? I did :)
    – raven
    Commented May 29, 2016 at 8:29
  • 1
    Yes I did. Actually, I'm using it quite often but just saw and corrected a typo. Of course the string containing the class names in the first line has to be made using " instead of '. Sorry about that.
    – nightlyop
    Commented May 30, 2016 at 8:37
30

Generally people do like

<div className={  `head ${style.class1} ${Style.class2}`  }><div>

OR

<div className={  'head ' + style.class1 + ' ' + Style.class2 }><div>

OR

<div className={  ['head', style.class1 , Style.class2].join(' ')  }><div>

But you can choose to Create a function to do this job

function joinAll(...classes) {
  return classes.join(" ")
}

then call it like:-

<div className={joinAll('head', style.class1 , style.class2)}><div>
29

This is how you can do that with ES6:

className = {`
      text-right
      ${itemId === activeItemId ? 'active' : ''}
      ${anotherProperty === true ? 'class1' : 'class2'}
`}

You can list multiple classes and conditions and also you can include static classes. It is not necessary to add an additional library.

Good luck ;)

3
  • 2
    This results in very ugly HTML, considering all the extra whitespace.
    – Nakedible
    Commented Oct 20, 2018 at 16:24
  • 3
    It is not necessary to written like that. This is just an example that better explain the solution. And always in production you have the minified version :) Commented Oct 20, 2018 at 16:50
  • 1
    string literals will not be minified in production. Commented Mar 4, 2021 at 12:49
24

Vanilla JS

No need for external libraries - just use ES6 template strings:

<i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
4
  • 1
    Vanilla JS is NOT ES6. But I do like your example.
    – RyanNerd
    Commented Aug 21, 2018 at 19:16
  • 14
    @RyanNerd Do you mean "ES6 is not vanilla JS"? Anyway, it is, because vanilla js means javascript without any frameworks. ES6 is a newer version of javascript. - stackoverflow.com/a/20435685/5111113
    – Huw Davies
    Commented Aug 22, 2018 at 3:49
  • Not a wrong answer but could be improved a lot. For example, everyone else added examples about states.
    – JGallardo
    Commented Oct 15, 2019 at 21:25
  • This looks quite clean, and better for this simple case for sure. But worth mentioning that when there are multiple classes that depends on states, template strings can become quite hard to write and worst to read. In those cases, using classnames library would make life easier. But again, for a simple example like that, template strings is the way to go for sure! Commented Feb 16, 2022 at 16:15
23

I don't think we need to use an external package for just adding multiple classes.

I personally use

<li className={`li active`}>Stacy</li>

or

<li className={`li ${this.state.isActive ? 'active' : ''}`}>Stacy<li>

or

<li className={'li ' + (this.state.isActive ? 'active' : '') }>Stacy<li>

the second and third one in case you need to add or remove classes conditionally.

3
  • 1
    this will add only one class either way. Commented Feb 5, 2020 at 7:39
  • 2
    @TrickOrTreat not true. all of the examples above will add two classes (provided isActive is true). Commented Sep 14, 2020 at 3:32
  • 1
    Why are there other answers at all besides this one?
    – nsndvd
    Commented Nov 16, 2020 at 15:19
20

Using CSS Modules (or Sass Modules) you can isolate your styling to a specific component too.

"Component-scoped CSS allows you to write traditional, portable CSS with minimal side effects: gone are the worries of selector name collisions or affecting other components’ styles."

import * as styles from "./whatever.module.css"  // css version
import * as styles from "./whatever.module.scss" // sass version

<div className={`${styles.class1} ${styles.class2}`}>
   INSERT YOUR CODE HERE
</div>

Ref1 Ref2

13

Maybe classnames can help you.

var classNames = require('classnames');
classNames('foo', {'xx-test': true, bar: false}, {'ox-test': false}); // => 'foo xx-test'
2
13

It can be done with https://www.npmjs.com/package/clsx :

https://www.npmjs.com/package/clsx

First install it:

npm install --save clsx

Then import it in your component file:

import clsx from  'clsx';

Then use the imported function in your component:

<div className={ clsx(classes.class1, classes.class2)}>
11

You could do the following:

<li key={index} className={`${activeClass} ${data.class} main-class`}></li>

A short and simple solution, hope this helps.

1
  • 1
    IMO this is the best answer! :) Commented Jun 21, 2020 at 19:26
9

Just adding, we can filter out empty strings.

className={[
    'read-more-box',
    this.props.className,
    this.state.isExpanded ? 'open' : 'close',
].filter(x => !!x).join(' ')}
9

You can create an element with multiple class names like this, I tryed these both way, its working fine...

If you importing any css then you can follow this way : Way 1:

import React, { Component, PropTypes } from 'react';
import csjs from 'csjs';
import styles from './styles';
import insertCss from 'insert-css';
import classNames from 'classnames';
insertCss(csjs.getCss(styles));
export default class Foo extends Component {
  render() {
    return (
      <div className={[styles.class1, styles.class2].join(' ')}>
        { 'text' }
      </div>
    );
  }
}

way 2:

import React, { Component, PropTypes } from 'react';
import csjs from 'csjs';
import styles from './styles';
import insertCss from 'insert-css';
import classNames from 'classnames';
insertCss(csjs.getCss(styles));
export default class Foo extends Component {
  render() {
    return (
      <div className={styles.class1 + ' ' + styles.class2}>
        { 'text' }
      </div>
    );
  }
}

**

If you applying css as internal :

const myStyle = {
  color: "#fff"
};

// React Element using Jsx
const myReactElement = (
  <h1 style={myStyle} className="myClassName myClassName1">
    Hello World!
  </h1>
);

ReactDOM.render(myReactElement, document.getElementById("app"));
.myClassName {
  background-color: #333;
  padding: 10px;
}
.myClassName1{
  border: 2px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-dom.production.min.js"></script>
<div id="app">
  
</div>

1
  • .join(' ') was nice. But we can avoid that and use template strings className={${styles.class1} ${styles.class2}} Commented Sep 23, 2020 at 10:32
8

This seem to work for me

<Link className={[classes.button, classes.buttonFirst]}>
3
  • 6
    in TypeScript this gives me : Type 'string[]' is not assignable to type 'string'.
    – nycynik
    Commented Jun 4, 2021 at 4:51
  • This method doesn't work with styled components and css helper
    – Baboo
    Commented Jul 28, 2022 at 14:50
  • just use a join(' ') after the array to and it solve it to simple Commented Dec 24, 2022 at 15:10
7

for more classes adding

... className={`${classes.hello} ${classes.hello1}`...
5

I know this is a late answer, but I hope this will help someone.

Consider that you have defined following classes in a css file 'primary', 'font-i', 'font-xl'

  • The first step would be to import the CSS file.
  • Then

<h3 class = {` ${'primary'} ${'font-i'} font-xl`}> HELLO WORLD </h3>

would do the trick!

For more info: https://www.youtube.com/watch?v=j5P9FHiBVNo&list=PLC3y8-rFHvwgg3vaYJgHGnModB54rxOk3&index=20

0
5

Create a function like this

function cssClass(...c) {
  return c.join(" ")
}

Call it when needed.

<div className={cssClass("head",Style.element,"black")}><div>
4

Late to the party, but why use third party for such a simple problem?

You could either do it as @Huw Davies mentioned - the best way

1. <i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
2. <i className={[styles['foo-bar-baz'], 'fa fa-user', 'fa-2x'].join(' ')}

Both are good. But writing can become complex for a large app. To make it optimal, I do the same above things but put it in a helper class

Using my below helper function, allows me to keep the logic separate for future editing, and also gives me multiple ways to add the classes

classNames(styles['foo-bar-baz], 'fa fa-user', 'fa-2x')

or

classNames([styles['foo-bar-baz], 'fa fa-user', 'fa-2x'])

This is my helper function below. I've put it in a helper.js where I keep all my common methods. Being such a simple function, I avoided using 3rd party to keep control

export function classNames (classes) {
    if(classes && classes.constructor === Array) {
        return classes.join(' ')
    } else if(arguments[0] !== undefined) {
        return [...arguments].join(' ')
    }
    return ''
}
4

You can use arrays and then join them using space.

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

This will result in :

<li key={index} class="activeClass data.class main-class"></li>
4

clsx makes this simple!

"The clsx function can take any number of arguments, each of which can be an Object, Array, Boolean, or String."

-- clsx docs on npmjs.com

Import it:

import clsx from 'clsx'

Use it:

<li key={index} className={clsx(activeClass, data.class, "main-class")}></li>
4

For this issue I use this util function:

export function cn(...args: string[]): string{
    return args.filter(Boolean).join(' ');
}

and apply it in this way:

<div className={cn(inter.className, styles.planColumns)}>
3

When I have many varying classes, I have found the following to be useful.

The filter removes any of the null values and the join puts all the remaining values into a space separated string.

const buttonClasses = [
    "Button", 
    disabled ? "disabled" : null,
    active ? "active" : null
].filter((class) => class).join(" ")

<button className={buttonClasses} onClick={onClick} disabled={disabled ? disabled : false}>
3

I used this syntax

    <div
      className={[
        "d-inline-flex justify-content-center align-items-center ",
        withWrapper && `ft-icon-wrapper ft-icon-wrapper-${size}`,
        wrapperClass,
      ].join(" ")}
    >
      <img
        className={`ft-icon ft-icon-${size} ${iconClass}`}
        alt={id}
        src={icon}
      />
    </div>
1
  • Both solutions (join and template literals) were already suggested. Please explain how yours is different Commented Jun 5, 2021 at 18:04
2

Using facebook's TodoTextInput.js example

render() {
    return (
      <input className={
        classnames({
          edit: this.props.editing,
          'new-todo': this.props.newTodo
        })}
        type="text"
        placeholder={this.props.placeholder}
        autoFocus="true"
        value={this.state.text}
        onBlur={this.handleBlur}
        onChange={this.handleChange}
        onKeyDown={this.handleSubmit} />
    )
  } 

replacing classnames with plain vanilla js code will look like this:

render() {
    return (
      <input
        className={`
          ${this.props.editing ? 'edit' : ''} ${this.props.newTodo ? 'new-todo' : ''}
        `}
        type="text"
        placeholder={this.props.placeholder}
        autoFocus="true"
        value={this.state.text}
        onBlur={this.handleBlur}
        onChange={this.handleChange}
        onKeyDown={this.handleSubmit} />
    )
  }
2

If you don't feel like importing another module, this function works like the classNames module.

function classNames(rules) {
    var classes = ''

    Object.keys(rules).forEach(item => {    
        if (rules[item])
            classes += (classes.length ? ' ' : '') + item
    })

    return classes
} 

You can use it like this:

render() {
    var classes = classNames({
        'storeInfoDiv': true,  
        'hover': this.state.isHovered == this.props.store.store_id
    })   

    return (
        <SomeComponent style={classes} />
    )
}
1
  • Why use closures if you can do the same with map or reduce? function classNames(rules) { return Object.entries(rules) .reduce( (arr, [cls, flag]) => { if (flag) arr.push(cls); return arr }, [] ).join(" ") } Commented May 26, 2020 at 19:33
2

Use https://www.npmjs.com/package/classnames

import classNames from 'classnames';

  1. Can use multiple classes using comas seperated:

    <li className={classNames(classes.tableCellLabel, classes.tableCell)}>Total</li>
    
  2. Can use multiple classes using comas separated with condition:

    <li className={classNames(classes.buttonArea, !nodes.length && classes.buttonAreaHidden)}>Hello World</li> 
    

Using array as props to classNames will also work, but gives warning e.g.

className={[classes.tableCellLabel, classes.tableCell]}
1
2

You can use react-directive, it supports all react elements and it even supports directives such as dirIf, dirShow, dirFor and extended className

You can do something like below:

import { useState } from 'react'
import directive from 'react-directive';

function Component() {
  const [isActive, setIsActive] = useState(true);
  const [isDisabled, setIsDisabled] = useState(false);

  return <directive.div className={{isActive, isDisabled}}>Contents</directive.div>;
}
// Renders <div class="isActive">Contents</div>

You can even supply some dependencies that will re-calculate the class names when any changes occurs. I am the author of the library.

Not the answer you're looking for? Browse other questions tagged or ask your own question.