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.