The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

An easy and elegant way to change a boolean useState value

posted on 19.2.2023 by Below Surface in "React"

const [uploadWindow, setUploadWindow] = useState(false);
return (
  <button onClick={() => setUploadWindow(!uploadWindow)}>Toggle it!</button>
)

The default value for uploadWindow is false. On button click, it will change to be NOT false -> true. The next time the button is clicked, the value of uploadWindow will be true and it will be changed to be NOT true -> false.

There you go!

Tags:

react
boolean
useState

More posts of this category

Conditionally add a HTML attribute in React

How to add a HTML attribute like "selected" to a HTML element

React

How to pass variables down to child components

Work with props in React/Next.js with TypeScript

React

Scroll to the page top after rendering a React component

Fix the annoying SPA issue and scroll to the top!

React

How I fixed the auto scroll bug of ReactQuill

Quill is a nice WYSIWYG text editor, but had a weird scroll bug

React