Search code examples
reactjsbuttononclicktoggleuse-state

How to toggle (change multiple times) data by using useState and onClick in React?


In react I have some data ("empty boxes") and a button. When I click on a button "empty boxes" changes to "full boxes". Next click nothing changes. ("full boxes" remains) But I want toggle that, each click must show me "empty boxes" or "full boxes" in turn. Can anyone help?

export default function App() {
  const [name, setName] = useState("empty boxes")
  const change = () => {
    setName("full boxes")
  }
  return (
   <main>
{name} 
<button onClick={change}>Change it!</button>
   </main>

  )
}

Solution

  • you should control your event by if

    const change = () => {
    if (name == "empty boxes")
    
      {setName("full boxes")}
    
    else { setName("empty boxes")}
    

    }