Menu
Coddy logo textTech

Toggle with State

Part of the Fundamentals section of Coddy's React journey — lesson 25 of 42.

State isn't only numbers. A boolean state is the standard switch for showing and hiding things:

const [isOpen, setIsOpen] = useState(false);

<button onClick={() => setIsOpen(!isOpen)}>Menu</button>
{isOpen ? <p>I am visible!</p> : null}

Two tricks working together:

  • setIsOpen(!isOpen): the ! flips the boolean, so one button both opens and closes
  • {condition ? jsx : null}: rendering null renders nothing; the element isn't hidden, it doesn't exist
challenge icon

Challenge

Medium

Build a spoiler reveal.

  1. Add boolean state revealed, starting false.
  2. The button (id="toggle") flips it on every click.
  3. When revealed, show a <p> with id="secret" and the text The cake is real; otherwise render null.

Try it yourself

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css" />
    </head>
    <body>
        <div id="root"></div>
        <script type="module" src="main.jsx"></script>
    </body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals