Solution
To add an active class on click in react js, use conditional rendering
based on the condition we can able to toggle or change any class in the react js.
In this article, we will create a clickable button and when users click on the button will change the background color of the button.
Snippet
In this snippet section, we will show those codes which are playing important role in this example.
Button Conditional Rendering
Here, we are adding the bg-color
class when the isActive
state is true else we adding an empty string.
<button className={isActive ? "bg-color" : ""} onClick={handleClick}>Click</button>
Changing isActive Flag on click
We have created a function where we are making isActive
- true
and false
based on the user clicking on the button.
const handleClick = () => {
setIsActive(!isActive);
};
Example
Below is a full example version of adding an active
class on click in react js.
Let’s start coding…
App.js
import { useState } from "react";
import "./styles.css";
export default function App() {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(!isActive);
};
return (
<div>
<button className={isActive ? "bg-color" : ""} onClick={handleClick}>
Click
</button>
</div>
);
}
styles.css
button {
padding: 5px;
width: 100px;
background-color: #f5a0ef;
}
.bg-color {
background-color: #94f0b9;
}
Output