close

How to add multiple classes to a ReactJS Component?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to add multiple classes to a ReactJS Component? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to add multiple classes to a ReactJS Component ?

  1. How to add multiple classes to a ReactJS Component ?

    add multiple classes to a ReactJS ComponentI am using React 16.6.3 and @Material UI 3.5.1, and is able to use arrays in className like className={[classes.tableCell, classes.capitalize]}

  2. add multiple classes to a ReactJS Component

    add multiple classes to a ReactJS ComponentI am using React 16.6.3 and @Material UI 3.5.1, and is able to use arrays in className like className={[classes.tableCell, classes.capitalize]}

Method 1

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'} />

Method 2

I am using React 16.6.3 and @Material UI 3.5.1, and is able to use arrays in className like className={[classes.tableCell, classes.capitalize]}

So in your example, the following would be similar.

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

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment