Open In App

How to add or remove multiple classes to a ReactJS Component?

Last Updated : 28 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

There are the following approaches to add or remove multiple classes to a ReactJS Component:

Approach 1: 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.

The argument ‘row’ is short for {row: true}. If the value associated with a given key is falsy, that key won’t be included in the output. The row and col are the names of classes in the following example.

classNames('row', 'col'); // => 'row col'
classNames('row', { col: true }); // => 'row col'
classNames({ 'row-col': true }); // => 'row-col'
classNames({ 'row-col': false }); // => ''
classNames({ row: true }, { col: true }); // => 'row col'
classNames({ row: true, col: true }); // => 'row col'

Module Installation:

We have to install dependency to use the classNames function, and we will be using bootstrap classes.

# via npm
npm install classnames 

# via Bower
bower install classnames

# via Yarn 
yarn add classnames

Filename: App.js

Javascript




import React, { Component } from "react";
// Importing classNames 
import classNames from 'classnames'
class GFG extends Component {
  state = {
    flag : true
  }
    
  handleUpdate = () => {
    this.setState({flag: !this.state.flag})
}
  
  render() {
   // Using classNames to add and remove
   // Classes based on state 
    var classes = classNames( {
      'btn': true,
      'btn-primary': this.state.flag === true,
      'btn-success':this.state.flag===false
    })
      
        return (
            <div>
               <button type="button" 
               className= { classes}
               onClick = {this.handleUpdate}>
              Click to add and remove classes 
                </button>  
            </div>
        );
  }
}
export default GFG;


File path: public/index.html 

HTML




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel = "stylesheet" href
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>


File path: src/Component/App.js

Javascript




import React from 'react'
import GFG from './GFG'
const App  = () => {
  
    return <div>
        <GFG />
    </div>
}
  
export default App;


File path: src/index.js

Javascript




import React, { Component } from 'react';
import   ReactDOM  from 'react-dom';
import App from './components/App'
  
ReactDOM.render(<App/> , document.querySelector('#root'))


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Approach 2: We can use the ES6 template literals.

Filename: App.js

Javascript




import React, { Component } from "react";
import './App.css'
class App extends Component {
  
  state = {
    flag: true
  }
  
  handleUpdate = () => {
    this.setState({ flag: !this.state.flag })
  }
  
  render() {
    return (
      <div className="appContainer" >
        <button type="button"
          // Using es6 backticks syntax(template literal)
          className={`btn ${this.state.flag ? 'box1' : 'box2'}`}
          onClick={this.handleUpdate}>
          Click to add and remove classes
         </button>
      </div>
    );
  }
}
  
export default App;


Filename: App.css

css




.appContainer{
  margin-left: 40%;
  margin-top: 50px;
}
  
.box1{
  background-color: green;
  padding: 10px;
}
  
.box2{
  background-color: yellow;
  padding: 10px;
}


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: 

  • Before button click
  • Now after clicking on the button, the following will be the output:

    After button click



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads