Home > Software design >  Change button 1 color onClick, then onClick of button 2, change button 2 color and change button 1 b
Change button 1 color onClick, then onClick of button 2, change button 2 color and change button 1 b

Time:05-31

New to coding and I'm trying to make it so you click on a button and it changes the color of that button, then when you click on the button right next to it, that button changes color and the previous button goes back to its original color. I've tried many, many different things, but this is what I have right now.

const [buttonOneOn, setButtonOneOn] = useState(false)
const [buttonTwoOn, setButtonTwoOn] = useState(false)

  function onChangeForFilter(e) {
    setButtonOneOn(prevButtonOn=>!prevButtonOn)
    if(buttonOneOn===true){
      e.target.style.color = "grey"
    }
    else{e.target.style.color='blue'}
    if(buttonTwoOn===true){
      setButtonOneOn(false)
    }
  }

  function onChangeForFilter2(e) {
    setButtonTwoOn(prevButtonOn=>!prevButtonOn)
    if(buttonTwoOn===true){
      e.target.style.color='grey'
    }
    else{e.target.style.color='blue'}
    if(buttonOneOn===true){
      setButtonOneOn(false)
    }
  }

Obviously this code doesn't do what I want to at all. Couldn't find any answers online. If anyone has any resources it would be appreciated.

CodePudding user response:

You can really attain that purely in css. heres some sample you can play. Let me know if this is what you mean.

button {
  background-color: white;
  border-radius: 10px;
  color: black;

}

button:focus  {
  background-color: red;
  border-radius: 10px;
  color: white;
}
<div>
  <button>My button 1</button>
  <button>My button 2</button>
  <button>My button 3</button>
</div>

  • Related