Skip to content
Related Articles

Related Articles

How to toggle CSS class on an element dynamically using ReactJS ?

View Discussion
Improve Article
Save Article
  • Last Updated : 17 Jun, 2022

In this article, we will learn to toggle the CSS class on an element dynamically in React.js. Sometimes developers need to give different CSS styling to the element while users take some particular action to make UI more attractive. For example, when the user clicks on one element we can change the styling for any particular element by toggling the CSS class.

Prerequisites: The prerequisites for this project are:

Creating Application: The below command will help you to start a new react app.

npx create-react-app testapp

Next, you must move to the testapp project folder from the terminal.

cd testapp

Project directory: It should look like this.

 

Approach 1: In this approach, we will implement the code to toggle between the single class. When a user clicks on the button, it will add and remove an active class from the <h1> elements.

Example: Write down the following codes in respective files.

  • App.js: In this file, we have implemented basic code to toggle between single classes.

Javascript




import React, { Component } from 'react';
import './App.css';
  
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isClassActive: false,
        };
    }
  
    // Function to toggle class
    toggleClass = () => {
        this.setState({ isClassActive: 
            !this.state.isClassActive });
    }
    render() {
        return (
            <div className='mainDiv'>
  
                {/* If isClassActive is true it will 
                    add active class to h1 otherwise it 
                    will remove active class */}
                <h1 className={this.state.isClassActive ? 
                'active' : ''}>
                    GeeksforGeeks
                </h1>
                <button className='button' 
                    onClick={this.toggleClass}>
                        Click to toggle class
                </button>
  
            </div>
        );
    }
}
  
export default App;

  • App.css: In this file, we have implemented different classes.

CSS




.mainDiv {
    margin: 20px auto;
    text-align: center;
}
  
.active {
    font-size: 40px;
    color: green;
}
  
.button {
    padding: 7px 10px;
    background-color: lightblue;
    color: red;
    border-radius: 2px;
}

Steps to Run: To start the react app, run the below command on your terminal and verify that react app is working fine.

npm start

Output:

 

Approach 2: In this approach, we will implement a toggle between multiple classes. We have numerous buttons, and when the user clicks on any button, we set the class according to the clicked button in the element.

Example: Write down the following codes in respective files.

  • App.js: In this file, we have implemented basic code to toggle between single classes.

Javascript




import React, { Component } from 'react';
import './App.css';
  
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentClass: 'black',
        };
    }
  
    // function to change class according to button click
    makeGreen = () => {
        this.setState({ currentClass: 'green' });
    }
    makeRed = () => {
        this.setState({ currentClass: 'red' });
    }
    makeYellow = () => {
        this.setState({ currentClass: 'yellow' });
    }
    makeBlue = () => {
        this.setState({ currentClass: 'blue' });
    }
    render() {
        return (
            <div className='mainDiv'>
  
                {/* class of element will be changed 
                    according to the button click */}
                <h1 className={this.state.currentClass}>
                    GeeksforGeeks
                </h1>
                <button className='button' 
                onClick={this.makeGreen}>
                    Make Green
                </button>
                <button className='button' 
                onClick={this.makeRed}>
                    Make Red
                </button>
                <button className='button' 
                onClick={this.makeYellow}>
                    Make Yellow
                </button>
                <button className='button' 
                onClick={this.makeBlue}>
                    Make Blue
                </button>
  
            </div>
        );
    }
}
  
export default App;

  • App.css: In this file, we have implemented different classes.

CSS




.mainDiv {
    margin: 20px auto;
    text-align: center;
}
  
.black {
    font-size: 20px;
    color: black;
}
  
.green {
    font-size: 40px;
    color: green;
}
  
.red {
    font-size: 60px;
    color: red;
}
  
.yellow {
    font-size: 30px;
    color: yellow;
}
  
.blue {
    font-size: 50px;
    color: blue;
}
  
.button {
    padding: 7px 10px;
    background-color: lightblue;
    color: red;
    border-radius: 2px;
    margin: 2px;
}

Steps to Run: To start the react app, run the below command on your terminal and verify that react app is working fine.

npm start

Output:

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!