How to add or remove multiple classes to a ReactJS Component?
Last Updated :
03 Oct, 2024
In react we offen need to add or remove multiple classes based on the state and props to update the content dynamically. It can be done with the help of template-literals, className property and by using external npm packages.
How to Add or Removed Classes in React?
To add or remove multiple classes to a React Component we will be using the bootstrap classes using CDN to show the dynamic updates. We will use the ES6 Template literals and the classname npm package to update the classes. Both these approaches are described below with example.
Steps to Create React Application
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: Install the Required Module
# via npm
npm install classnames
# via Bower
bower install classnames
# via Yarn
yarn add classnames
Project Structure:

The updated dependencies in the package.json file are
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"classnames": "^2.5.1",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Approach 1: Using classnames package with bootstrap
We can use the classNames Method (A simple JavaScript utility for conditionally joining classNames together). The classNames function takes any number of arguments which can be a string or object.
Example: This example uses the classnames npm package to dynamically remove and add bootstrap classes to React component.
HTML
<!-- Filename - public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
/>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
JavaScript
// Filename: App.js
import React from "react";
import GFG from "./GFG";
const App = () => {
return (
<div>
<GFG />
</div>
);
};
export default App;
JavaScript
// Filename: GFG.js
import React, { useState } from "react";
// Importing classNames
import classNames from "classnames";
const GFG = () => {
// Using useState hook for managing the flag state
const [flag, setFlag] = useState(true);
// Function to toggle the flag state
const handleUpdate = () => {
setFlag(!flag);
};
// Using classNames to add and remove classes based on state
const classes = classNames({
btn: true,
"btn-primary": flag === true,
"btn-success": flag === false
});
return (
<div>
<button type="button" className={classes} onClick={handleUpdate}>
Click to add and remove classes
</button>
</div>
);
};
export default GFG;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:

Approach 2: Using ES6 Template Literals with Custom Classes
We can use the ES6 template literals as given in below example.
Example: This example uses ES^ template literals with custom classes to add and remove muliple classes from react component.
CSS
/* Filename - App.css */
.appContainer {
margin-left: 40%;
margin-top: 50px;
}
.box1 {
background-color: green;
padding: 10px;
color: white;
}
.box2 {
background-color: yellow;
padding: 10px;
color: black;
}
JavaScript
// Filename: App.js
import React, { useState } from "react";
import "./App.css";
const App = () => {
// Using useState hook to manage the flag state
const [flag, setFlag] = useState(true);
// Function to toggle the flag state
const handleUpdate = () => {
setFlag(!flag);
};
return (
<div className="appContainer">
<button
type="button"
// Using ES6 template literals to toggle class names
className={`btn ${flag ? "box1" : "box2"}`}
onClick={handleUpdate}
>
Click to add and remove classes
</button>
</div>
);
};
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Similar Reads
How to Add a classname/id to React-Bootstrap Component ?
In this article, we will learn how we can add a class name and ID to a React-Bootstrap component. ClassName and ID can be used to target elements while styling and scripting (which means writing logic) the application. Prerequisites:React JSReact-BootstrapSteps to create React app and install bootst
4 min read
How to add a CSS class whenever the component is updated in React JS ?
In this article, we will learn how to add a CSS class conditionally in React JS. If we want to update/add a CSS class when the component is updated or the state/props of components change then we have to conditionally apply the CSS based on the state/props value. Syntax of adding CSS classes condit
2 min read
How to update the State of a component in ReactJS ?
To display the latest or updated information, and content on the UI after any User interaction or data fetch from the API, we have to update the state of the component. This change in the state makes the UI re-render with the updated content. Prerequisites: NPM & Node.jsReact JSReact StateReact
3 min read
How to combine multiple reducers in ReactJS ?
To combine multiple reducers in React JS we have a function called combineReducers in the redux. This basically helps to combine multiple reducers into a single unit and use them. Approach In React, to combine and implement multiple reducers combineReducers methods are used. It manages multiple redu
4 min read
How To Conditionally Add Attributes To React Components?
In React, it's common to render components based on certain conditions dynamically. Often, you may need to add or remove attributes to a React component based on the application's state, the props passed down, or other factors. Handling these dynamic conditions effectively is key to building flexibl
3 min read
How to optimize React component to render it ?
ReactJS mainly depends upon the props (which are passed to it) and the state of the Component. Hence to reduce the number of times Component renders we can reduce the props and state it depends upon. This can be easily done by separating the logic of one component into several individual child compo
3 min read
When to use a Class Component over a Function Component in ReactJS?
ReactJS provides two main ways to create components: Class Components and Function Components. With the introduction of React Hooks in version 16.8, Function Components became more powerful and are now commonly preferred. However, there are still scenarios where Class Components might be a better ch
3 min read
How to add Stateful component without constructor class in React?
Generally, we set the initial state of the component inside the constructor class and change the state using the setState method. In React basically, we write HTML-looking code called JSX. JSX is not a valid JavaScript code but to make the developer's life easier BABEL takes all the responsibility t
2 min read
How to convert functional component to class component in ReactJS ?
ReactJS offers two primary ways of creating components: functional components and class components. While functional components are more concise and easier to reason about, there are situations where class components may be necessary with the flexibility to use lifecycle methods and manage the state
2 min read
How to Create a Toggle Switch in React as a Reusable Component ?
Creating a reusable toggle switch in React enhances the UI. This component can customized as required with the props and can be reused. It can be done using CSS or CSS frameworks like MUI and tailwindCSS. In this article, weâre going to create a Toggle Switch in React as a reusable component. Prereq
3 min read