score:2

Accepted answer
export default function Button({ lightAPI, index, lightList, setLightList }) {
  const [buttonColor, setButtonColor] = useState(green);

  const handleColorChange = (e)=> {
    const newButton = e.target.style.backgroundColor;
    const newColor = buttonColor === green ? red : green;
    setButtonColor(newColor);
    if (newColor === green) {
      if (!lightList.includes(lightAPI.id)) {
        // add the id only if it does not existss in lightList
        setLightList([...lightList, lightAPI.id])
      }
    }
    else {
      if(lightList.includes(lightAPI.id)){
        // filter out the ID to remove
        const newList = lightList.filter((lightID) => lightID !== lightAPI.id)
        setLightList(newList)
      }
    }
  }

  return (
    <div>
      <button
        style={{ backgroundColor: buttonColor }}
        color={buttonColor}
        onClick={handleColorChange}
        index={index}
      ></button>
    </div>
  );
}

Related Query

More Query from same tag