Home > Blockchain >  5 buttons in separate components change color one at a time triggered by an onclick
5 buttons in separate components change color one at a time triggered by an onclick

Time:11-15

export default function ChatButton({showScreen}) {
  const [active4, setActive4] = useState(false);
  const handleClick4 = () => {
    setActive4((prev) => !prev);
    showScreen("MessageScreen");
  };

  return (
    <div id="chat-button">
      <div
        className="button-4"
        type="button"
        name="chat"
        onClick={handleClick4}
        style={{
          backgroundColor: active4 ? "red" : "black",
          borderRadius: "25px",
          border: active4 ? "2px solid #e32828f7" : "none",
        }}
      ></div>
    </div>
  );
}

in this picture it shows one component of a button the and the other four is , ,

which is render in a Button component and almost same code

export default function Buttons({ showScreen}) {


  
  return (
    <div id="pda-buttons">
      <div className=" row-1">
        <div className="buttns d-inline-flex">
          <li className="button-list d-flex justify-content-evenly mt-1">
            <MailButton showScreen={showScreen} />
            <VoiceMailButton showScreen={showScreen} />
            <PhoneButton showScreen={showScreen} />
            <ChatButton showScreen={showScreen} />
            <MapButton showScreen={showScreen} />
          </li>
        </div>
      </div>
    </div>
  );
}

The propblem is everytime I click one of the the buttons it is working it changes the color of the button that i click but when I click another button it changes the color but the previous color doesnt return to its previuos color the main issue is I want to only one to changes color everytime i click and the other should return to its original form unless it is click

is there a way to solve it in a simple way

CodePudding user response:

There seems to be no problem at all. This is how react works. When you change a button component's state it won't reset until it's parent component or itself re-renders. If you want the children to control other children's states (Button components in this case) there are some techniques. But what I can suggest is that you reconsider your components and lift up the state of each component's active state to their parent. When a child mutates their slice in the parent state to true the others will also be changed to false.

CodePudding user response:

if I understand your question right you want the styles of the clicked button to be applied on one button at a time

if you want to do so you can save a state in buttons component like

const [choice,setChoice]=useState()

and then send your choice and setChoice() to each child , if the choice is empty or it's value=name of current component set the styles you want else don't and use setChoice() whenever you call handleClick4() to save which component is the your current choice

  • Related