How to change background color on click in react js?
May 01, 2022Hi Friends π,
Welcome To aGuideHub! β€οΈ
Today, I am going to show you. how to change background color on click in react js with code example.
In this article, we will create a simple change background color on click in React.js just like you would create in a normal HTML project.
Letβs look at the following example to understand how it basically works:
APP.js
import {useState} from 'react';
export default function App() {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
// ποΈ toggle
setIsActive(current => !current);
// ποΈ or set to true
// setIsActive(true);
};
return (
<div>
<div
style={{
backgroundColor: isActive ? 'salmon' : '',
color: isActive ? 'white' : '',
}}
onClick={handleClick}
>
Click here
</div>
</div>
);
}
We set the onClick
prop on the element, so every time it is clicked, the handleClick
function is invoked.
In our handleClick
function, we simply toggle the isActive
state.
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:
Check the output of the above code example.
All the best π