Home > Mobile >  Is there any way I can change css by clicking event without using state in react?
Is there any way I can change css by clicking event without using state in react?

Time:04-13

I'm making a chip component, and I want to make it reusable. Since the state is not used in every component which uses this chip component, I don't want to use state and change the background color when it's clicked and un-clicked. How can I use it without using the react-hook state? I'm using emotion/react(typescript) for this project now.

Unclicked Chip example

Clicked Chip example

CodePudding user response:

You could use the CSS with a hidden checkbox trick. It uses a hidden HTML checkbox that is toggled on and off when you click the component.

An alternative solution would be to make the component handle its own state (i.e. not dependent on the state of its parent component).

CodePudding user response:

You can change the className using react useState.

    const [classState,setClassState] = useState(false)
    const someFunc = () => {
     setClassState(!classState)
}

<div className={classState ? "firstClass" : "secondClass"}></div>
  • Related