Home > Mobile >  How to change the style of an element when clicked in React
How to change the style of an element when clicked in React

Time:12-18

I'm trying to figure out how to change the colour style of a checkbox when clicked on, in react. It should also toggle back to the old colour when clicked again.

function handleClick() {
     DO SOMETHING HERE TOGGLE THE FILL COLOR
  }

  <CheckCircle onClick={handleClick} style={{ fill: colors.orange }} 

CodePudding user response:

You can use a state for this.

Define the state in your component:

const [clicked, setClicked] = useState(false)

The handleClick funtion would look like this:

function handleClick() {
    setClicked(!clicked);
}

Finally use the clicked variable to adjust your style. Maybe something like this:

<CheckCircle onClick={handleClick} style={{ fill: clicked ? colors.orange : colors.red }} />

CodePudding user response:

const [isChecked, setIsChecked] = useState(true)

function handleOnClick() {
  setIsChecked(prevState => !prevState)
}

return <CheckCircle onClick={handleOnClick} style={{ fill: isChecked ? colors.orange : OTHER_COLOR }} />
  • Related