Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react change color of a single element with index

I just started learning react 2 days ago, and I am trying to change the color of a button on click. I have 2 buttons, each of them should change color when clicked, however, my code changes the color of both when I just click one. I read that I need to use an index somewhere, but I am not sure where or how to map the index. Any help will be much appreciated. here’s my code:

let ash = "#959595";
let purple = "#8c52ff";

const [buttonColor, setButtonColor] = useState(ash);

function handleColorChange(e) {
    const button = e.target.style.backgroundColor;
    const newButton = e.target.style.backgroundColor;

    const newColor = buttonColor === ash ? purple : ash;
    setButtonColor(newColor);
}

return (
    <div>
        <button
            className="days-btn"
            style={{ backgroundColor: buttonColor }}
            color={buttonColor}
            onClick={handleColorChange}
        >
            M
        </button>
        &nbsp;
        <button
            className="days-btn"
            style={{ backgroundColor: buttonColor }}
            color={buttonColor}
            onClick={handleColorChange}
        >
            T
        </button>
    </div>
);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue is two buttons share the same state. You can keep the color-changing logic in a separate Button component. So Buttons can change their color independently.

import { useState } from "react";

let ash = "#959595";
let purple = "#8c52ff";

const Button = ({ buttonText }) => {
  const [buttonColor, setButtonColor] = useState(ash);

  function handleColorChange(e) {
    const newColor = buttonColor === ash ? purple : ash;
    setButtonColor(newColor);
  }

  return (
    <button
      className="days-btn"
      style={{ backgroundColor: buttonColor }}
      color={buttonColor}
      onClick={handleColorChange}
    >
      {buttonText}
    </button>
  );
};

export default Button;

In your other component create two buttons giving any props as you need.

import Button from "./Button";

const App = () => {
  return (
    <div>
      <Button buttonText="M" />
      <Button buttonText="T" />
    </div>
  );
};

export default App;

Code Sandbox

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading