Booleans in State
A state that's true or false is just right for anything that's on or off: details shown or hidden, a band among your favorites or not, a menu open or closed.
const [showDetails, setShowDetails] = useState(false);
function handleToggle() {
setShowDetails(!showDetails);
}
return (
<article className="card">
<h2>Tin Robots</h2>
<button onClick={handleToggle}>
{showDetails ? "Hide details" : "Show details"}
</button>
{showDetails && <p>Tent, Saturday 21:00</p>}
</article>
);!showDetails is the opposite of what it is now: false becomes true, and true becomes false. So one button opens the details, and the same button closes them.
What the page shows is decided by the conditions from the Lists and Conditions lesson: ? : picks the button's text, and && shows the paragraph only while showDetails is true. When it's false, the paragraph isn't hidden: it isn't on the page at all.
That's how React apps usually work. The state says how things are, and the JSX describes what the page looks like in each case. You don't add or remove elements yourself. You change the state, and React does the rest.
A boolean can also choose a class, so that CSS styles the element differently:
<article className={favorite ? "card favorite" : "card"}>Give booleans names that answer yes or no: showDetails, favorite, isOpen. Then showDetails && … reads almost like a sentence.
Instructions
A click on Show details shows a paragraph Main Stage, Saturday 22:30 under the buttons, and the button then says Hide details. Another click hides the paragraph again, and the button says Show details. Use a state showDetails that starts as false.
The star marks the band as a favorite. A click changes ☆ to ★ and gives the article the class favorite, and another click changes it back. Use a second state, favorite.