Home / Snippets / How to add multiple classes to a ReactJS Component?
How to add multiple classes to a ReactJS Component? cover

How to add multiple classes to a ReactJS Component?

1.5K

2 years ago

0 comments

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 });
notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this