Change background color on Click in React

avatar

Borislav Hadzhiev

Last updated: Apr 28, 2022

banner

Photo from Unsplash

Change background color on click in React #

To change background color on click in React:

  1. Set the onClick prop on the element.
  2. When the element is clicked, set the active state.
  3. Use a ternary operator to conditionally set the background color based on the state variable.
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} > Hello world </div> </div> ); }

change background color on click

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.

You could set the state to active, e.g. setIsActive(true), if you don't want to change the background color every time the element is clicked.

We used a ternary operator to conditionally set the backgroundColor style on the element.

App.js
<div style={{ backgroundColor: isActive ? 'salmon' : '', color: isActive ? 'white' : '', }} onClick={handleClick} > Hello world </div>

The ternary operator is very similar to an if/else statement.

It checks if the value to the left of the question mark is truthy, and if it is, the operator returns the value to the left of the colon, otherwise the value to the right is returned.

In other words, if the isActive variable stores a true value, we set the backgroundColor property to salmon, otherwise set it to an empty string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.