How to toggle a class in React
In this tutorial, we are going to learn about how to dynamically toggle classes in the React app.
Toggling the class
To toggle a class, we need to use the boolean value in the ternary expression.
-
If the boolean value is
true
class name is added to the react element. -
If the boolean value is
false
class name is removed from the react element.
Here is an example that uses react hooks, which add the class name app
to a div
element when we click on a Toggle class
button. If we click that button again class name is removed from the div
element.
import React, { useState } from "react";import "./styles.css";
export default function App() {
const [isActive, setActive] = useState("false");
const handleToggle = () => {
setActive(!isActive); };
return (
<div className={isActive ? "app" : null}> <h1>Hello react</h1>
<button onClick={handleToggle}>Toggle class</button> </div>
);
}
In class-based components, you can do it like this.
import React, { Component } from "react";
import "./styles.css";
class App extends Component {
state = { isActive: false };
handleToggle = () => {
this.setState({ isActive: !this.state.isActive }); };
render() {
const isActive = this.state.isActive;
return (
<div className={isActive ? "app" : null}> <h1>Hello react</h1>
<button onClick={this.handleToggle}>Toggle class</button> </div>
);
}
}
export default App;
Toggle between two classnames
Instead of adding or removing a class name, we can also toggle between two class names in react app.
In this below example, by default container
class is added to the div
element, when we click on a Toggle class
button container
class is removed, the app
class is added to the element.
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [isActive, setActive] = useState("false");
const handleToggle = () => {
setActive(!isActive);
};
return (
<div className={isActive ? "app" : "container"}> <h1>Hello react</h1>
<button onClick={handleToggle}>Toggle class</button>
</div>
);
}
Adding a classname to the existing class name
You can also add a new class name to the existing class name like this.
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [isActive, setActive] = useState("false");
const handleToggle = () => {
setActive(!isActive);
};
return (
<div className={`app ${isActive ? "danger" : ""}`}> <h1>Hello react</h1>
<button onClick={handleToggle}>Toggle class</button>
</div>
);
}
Intially rendered html
<div class="app">
<h1>Hello react</h1>
<button>Toggle class</button>
</div>
After clicking the Toggle class
button html looks like this.
<div class="app danger"> <h1>Hello react</h1>
<button>Toggle class</button>
</div>