Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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>
);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!