Posts Learn Components Snippets Categories Tags Tools new About

How to add multiple classes to a ReactJS Component?

Get to know how to add multiple classes to a react js Component using these easy methods

Created on Jan 31, 2022


In this short snippet, you will learn how to add multiple classes into React component and basically any HTML element tag that's on your react project. It's 

ES6 Template Literals

<div className={`${styles.class1} ${styles.class2}`}></div>

<div className={`${class1} anotherClass ${class1}`}></div>

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

<li className={`li ${this.state.isActive ? 'active' : ''}`}>Stacy<li>
By using ES6 template literal you can add multiple classes to the HTML tag.

Pass Comma Separated Array

<Link className={[classes.button, classes.buttonFirst]}>

<Link className={['first', 'second']}>
Other than that you can pass it in as an array and separated it by a comma.

Using classnames Library

Another way is to use classnames library and with it, you can also toggle classes depending on the state of your component.
# via npm
npm install classnames

# or Yarn (note that it will automatically save the package to your `dependencies` in `package.json`)
yarn add classnames
And the way you define a class is like the following.
var classNames = require('classnames');
classNames('foo', 'bar'); // => 'foo bar'
And for the dynamic class name, you can refer to the code below.
let buttonType = 'primary';
classNames({ [`btn-${buttonType}`]: true });

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️