Home > Back-end >  how to change one button text color to red and rest of button text color to black after click in Rea
how to change one button text color to red and rest of button text color to black after click in Rea

Time:07-05

I'm having a question about how to change one button text color to red and rest of button text color to black at the same time after click in React. All buttons must be created within a map function. I created a sandbox enter image description here

After click button3, button2 change to black and button3 now is red like above image enter image description here

Any helps would be thankful!!!

CodePudding user response:

You need to keep the state of which component is selected in the parent.

  const [selectedIndex, setSelectedIndex] = useState();

Then you can determine which one should be colored, and send that down as a prop.

{fake.map((value, index) => {
  return <Circles isSelected={index===selectedIndex} onClick={() => setSelectedIndex(index)} />
}}

CodePudding user response:

selected index should be stored in parent component:

// Parent component
export default function App() {
  const [clickedIndex, setClickedIndex] = React.useState(null);
  const fake = [1, 2, 3, 4, 5];

  const click = (index) => {
    console.log("clicked "   index);
    setClickedIndex(index);
  };

  return (
    <div className="App">
      {fake.map((value, index) => {
        return (
          <Circles
            key={index}
            index={index}
            clickedIndex={clickedIndex}
            onClick={() => click(index)}
          ></Circles>
        );
      })}
    </div>
  );
}
// Child component
export default function Circle(props) {
  const { index, clickedIndex, onClick } = props;
  const isMeClicked = index === clickedIndex;
  return (
    <div className="App">
      <button
        onClick={onClick}
        style={{ color: isMeClicked ? "red" : "black" }}
      >
        Circle{index}
      </button>
    </div>
  );
}
  • Related