Coding for All
Lesson 8: Showing and Hiding
Showing and Hiding Let state decide what appears on screen at all.
1import { useState } from 'react';
2
3function App() {
4 const [open, setOpen] = useState(false);
5 return (
6 <div>
7 <button onClick={() => setOpen(!open)}>
8 {open ? 'Hide' : 'Show'} the secret
9 </button>
10 {open && <p>React was almost called FaxJS!</p>}
11 </div>
12 );
13}
14export default App;
Terminal
$ npm run dev
VITE v5.4 ready in 312 ms
Local: http://localhost:5173/
(your app is live: look at the browser window above!)
Every line, explained
import { useState } from 'react';
useState comes from the React library itself. This locked import line brings it in; you'll use it a few lines down.
function App() {
The App component: every lesson's page starts from this function.
const [open, setOpen] = useState(false);
A boolean piece of state: is the secret showing right now? It starts false: hidden.
return (
When JSX spans several lines, it goes inside round brackets after return. The brackets keep the JSX attached to the return: without them, JavaScript would think the return finished at the end of that line and hand back nothing.
<div>
A component must return ONE outer tag. Putting two siblings side by side at the top level is an error, so a wrapping <div> holds them together.
<button onClick={() => setOpen(!open)}>
The click handler flips the boolean: !open is the opposite of open (the ! flips a boolean: NOT). Click: false becomes true. Click again: back to false.
{open ? 'Hide' : 'Show'} the secret
A ternary: condition ? valueIfTrue : valueIfFalse. It is an if/else squeezed into an expression, perfect inside JSX. The button relabels itself depending on the state.
</button>
Close the button tag.
{open && <p>React was almost called FaxJS!</p>}
Conditional rendering: with &&, the paragraph only renders when open is true; when it is false, React renders nothing at all there. State isn't just changing text any more; it decides what exists on the page. TRY IT!
</div>
Closing tag for the wrapping div.
);
The ); closes the return's round bracket.
}
This } closes the component function.
export default App;
export default App hands your component to the rest of the app. A locked line in every lesson: the app's starter file (main.jsx) imports App and mounts it on the page.