Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to add a CSS class whenever the component is updated in...

How to add a CSS class whenever the component is updated in ReactJS ?

If we want to update/add 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. 

Here is a simple example of adding CSS classes conditionally.

 <div className={`box ${flag === false ? "" : "hidden"}`}>

The class hidden will be applied when the value of the flag is true otherwise only the box CSS class will be applied.

Creating 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

Project Structure: It will look like the following.

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

App.js




import React, { Component } from 'react';
import styles from './index.css';
  
class App extends Component {
    state = {
        flag: true
    };
  
    handleUpdate = () => {
        this.setState(prevstate => ({ flag: !prevstate.flag }));
    };
  
    render() {
        const flag = this.state.flag;
        return (
            <div>
                <button onClick={this.handleUpdate}>Show Box</button>
                <div className={`box ${flag === false ? "" : "hidden"}`}>
                    <p>click on button to hide and show the box</p>
                </div>
            </div>
        );
    }
}
  
export default App;


index.css




.box{
  width: 100px;
  height: 200;
  padding: 20px;
  border: 1px solid black;
}
.hidden {
  display: none;
}


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

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

As we can see from the above output the box will disappear when the CSS class hidden will be added to the HTML element based on the updated value of the state.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments