Soumi Ghosh
Soumi Ghosh

Reputation: 129

Change background color of div by clicking in react

I have three div in the component(which can be more than three as well). I want to change their color when they will be clicked. If again I will click, they will get back their old color. In my code if I am clicking any one div, all div s are changing, Can you help me to do it for particular div? The code is:

import React,{useState} from 'react'

export default function ChangeColor() {
   let [colorState,changeState]=useState(['red','green','blue']);
   let [isActive,setIsActive]=useState(true);

  return (
    <>
      {colorState.map((color,index)=>{      
        return(
        <React.Fragment key={index}>            
           <div style={{width:'100px',height:'100px',backgroundColor:isActive?`${color}`:'yellow' }} 
           onClick={()=>{isActive?setIsActive(false) :setIsActive(true)}}>
             <p>{color}</p>
           </div>
        </React.Fragment>
      )})
      }
   
    </>
  )
}

Upvotes: 1

Views: 1907

Answers (1)

John Li
John Li

Reputation: 7447

All 3 div are changing together because only a single value is used to control the state.

To solve this, you could make isActive an object that contain a Boolean value for each color, so its structure could be something like this:

{red: true, green: false, blue: false}

This way, each of the div can set the styles based on condition like:

backgroundColor: isActive[color] ? 'yellow' : color

Full example: (live demo on stackblitz)

import React, { useState } from 'react';

export default function ChangeColor() {
  const [colorState, changeState] = useState(['red', 'green', 'blue']);
  const [isActive, setIsActive] = useState({});

  const toggleActive = (color) =>
    setIsActive((prev) => {
      if (prev[color]) return { ...prev, [color]: false };
      return { ...prev, [color]: true };
    });

  return (
    <>
      {colorState.map((color, index) => {
        return (
          <React.Fragment key={index}>
            <div
              style={{
                width: '100px',
                height: '100px',
                backgroundColor: isActive[color] ? 'yellow' : color,
                cursor: 'pointer',
              }}
              onClick={() => toggleActive(color)}
            >
              <p>{isActive[color] ? 'yellow' : color}</p>
            </div>
          </React.Fragment>
        );
      })}
    </>
  );
}

Upvotes: 2

Related Questions