javascript / beginner
Snippet
Toggling Boolean State for Conditional Overlay Visibility
Boolean datatypes in React state provide a clean way to handle toggleable UI components. Using logical AND (&&) with a boolean flag conditionally renders elements only when the flag is true.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { useState } from 'react';export function ModalController() {const [isOpen, setIsOpen] = useState(false);return (<div><button onClick={() => setIsOpen((prev) => !prev)}>Toggle Dialog</button>{isOpen && <aside className="dialog-box">Modal Content</aside>}</div>);}
react
Breakdown
1
const [isOpen, setIsOpen] = useState(false);
Initializes a boolean state variable to store whether the modal is visible or hidden.
2
<button onClick={() => setIsOpen((prev) => !prev)}>
Inverts the current boolean state value whenever the button is clicked.
3
{isOpen && <aside className="dialog-box">Modal Content</aside>}
Conditionally outputs the modal markup only when isOpen evaluates to true.