Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

you should control your event by if

const change = () => {
if (name == "empty boxes")

  {setName("full boxes")}

else { setName("empty boxes")}

}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading