How to change background color on click in react js?

Hi 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:


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 (
          backgroundColor: isActive ? 'salmon' : '',
          color: isActive ? 'white' : '',
        Click here

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.

React, Click, Text

React, Background, Color

All the best πŸ‘

Premium Content

You can get all the below premium content directly in your mail when you subscribe us


Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts