How to add multiple CSS classes in React
Tags: react, css
Published: 2021-09-24 05:40:58

You might have come across scenarios where you would want to add multiple CSS classes to an HTML element based on some condition. In this tutorial, we will see different ways of adding multiple CSS classes in React.

# Setting up the project

Create a new react app using the following command:

```bash
npx create-react-app react-multiple-class
```

Update `index.css` with the following styles, which will be used in demonstrating how to use multiple classes:

```css
body {
  margin: 10px auto;
  max-width: 800px;
}

.box {
  border: 1px solid;
  border-radius: 5px;
  padding: 1rem;
  margin: 0.5rem;
}

.success {
  color: #0f5132;
  background-color: #d1e7dd;
  border-color: #badbcc;
}

.error {
  color: #842029;
  background-color: #f8d7da;
  border-color: #f5c2c7;
}

.warning {
  color: #664d03;
  background-color: #fff3cd;
  border-color: #ffecb5;
}
```

# Adding classes statically

Adding classes statically is straightforward and is the same as how we add them in HTML.

Update the `App.js` component as shown below:

```jsx
function App() {
  return <div className="box success">This is a success message</div>
}

export default App
```

If you run the application now, you should be able to see that both the classes 'box' and 'success' applied.

![static classes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49iyfthsnbtlxxqrdfw6.png)

# Adding classes dynamically

Most of the time you would want to add a class dynamically based on some condition. There are multiple ways in which this can be achieved:

## Using String Interpolation (Template Literals)

[Template strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) can be used when you need to evaluate certain expressions and output the result:

```jsx
import { useState } from "react"

function App() {
  const [isWarning] = useState(true)
  return (
    <>
      <div className="box success">This is a success message</div>
      <div className={`box ${isWarning === true && "warning"}`}>
        This is a warning message
      </div>
    </>
  )
}

export default App
```

In the above example, warning class will be added only when the `isWarning` state is true. Alternatively, we could write this as `box ${isWarning && "warning"}` as we don't need to explicitly check since `isWarning` is boolean.

## Using props from the parent component

We can use the props passed from the parent component and use it in providing the class name:

```jsx
const ChildComp = props => {
  return <div className={`box ${props.status}`}>This is an error message</div>
}

function App() {
  return <ChildComp status="error" />
}

export default App
```

# Using classnames library

There is a handy library named [classnames](https://www.npmjs.com/package/classnames), which can be used if there are many classes and complex conditions.

First, let's install the package in our project using the following command:

```bash
yarn add classnames
```

Now use it in the `App.js` as follows:

```jsx
import classNames from "classnames"
import { useState } from "react"

function App() {
  const [isWarning] = useState(true)
  return (
    <div className={classNames("box", { warning: isWarning })}>
      This is a warning message
    </div>
  )
}

export default App
```

Here since the value of `isWarning` is true, the 'warning' class will be added to the div.

Classnames library can take a lot of arguments as shown below:

```js
classNames("foo", { bar: true, duck: false }, "baz", { quux: true }) // => 'foo bar baz quux'
```

# Source code

You can view the source code [here](https://github.com/collegewap/react-multiple-class).