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>
<button
className="days-btn"
style={{ backgroundColor: buttonColor }}
color={buttonColor}
onClick={handleColorChange}
>
T
</button>
</div>
);
The issue is two buttons share the same state. You can keep the color-changing logic in a separate Button
component. So Button
s 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