Chapter 4 of 4
Putting It Together
A short review of the pieces and how they combine into an interactive component.
Events and conditionals are the two halves of interactivity: an event changes state, and the conditional decides what the new state looks like on screen.
import { useState } from "react";
function PasswordField() {
const [value, setValue] = useState("");
const [isVisible, setIsVisible] = useState(false);
const isTooShort = value.length > 0 && value.length < 8;
return (
<div>
<input
type={isVisible ? "text" : "password"}
value={value}
onChange={(event) => setValue(event.target.value)}
aria-invalid={isTooShort}
/>
<button type="button" onClick={() => setIsVisible(!isVisible)}>
{isVisible ? "Hide" : "Show"}
</button>
{isTooShort && <p role="alert">Use at least 8 characters</p>}
</div>
);
}Notice what is not in state
isTooShort is derived during render rather than stored. There is no way for it to fall out of sync with value, and no handler has to remember to update it.
What you have learned
- Event props take a function and receive a synthetic event.
preventDefaultstops the browser default;stopPropagationstops the bubble.- Use a ternary for either/or,
&&for show-or-nothing, and early returns for loading and error paths. - A changing
keyremounts a subtree, which is the tidiest way to reset it.