Lesson 161 of 296
Events and conditional rendering
What you will learn
- Handling events in React
- Typing event objects
- Preventing default behaviour
- Showing or hiding UI with conditions
- The
0 &&trap - Returning null
On this page
Handling events
Pass a function to an event prop such as onClick, onChange or onSubmit:
function SaveButton({ onSave }: { onSave: () => void }) {
function handleClick() {
onSave();
}
return <button type="button" onClick={handleClick}>Save</button>;
}Pass the function, do not call it:
onClick={handleClick} correct: React calls it on click
onClick={handleClick()} wrong: runs during render, and the result is used as the handler
onClick={() => remove(id)} correct: an arrow function when you need argumentsThe event object
React passes an event object, similar to the DOM event (Lesson 88). It is a synthetic event: React's cross-browser wrapper with the same main properties.
import type { ChangeEvent, FormEvent } from "react";
function SearchBox({ onSearch }: { onSearch: (query: string) => void }) {
const [query, setQuery] = useState("");
function handleChange(e: ChangeEvent<HTMLInputElement>) {
setQuery(e.target.value);
}
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
onSearch(query.trim());
}
return (
<form onSubmit={handleSubmit} role="search">
<label htmlFor="q">Search</label>
<input id="q" value={query} onChange={handleChange} />
<button type="submit">Go</button>
</form>
);
}e.preventDefault()stops the page reloading on submit (Lesson 88).- Listen to
onSubmiton the form, notonClickon the button (so Enter works). - React's
onChangeon inputs fires on every keystroke (like the DOMinputevent), not only when focus leaves.
Event delegation (Lesson 88) is handled by React internally: you attach handlers to elements, and React manages listeners at the root for you.
Conditional rendering
Ternary: choose between two things.
function LoginStatus({ user }: { user: { name: string } | null }) {
return <p>{user ? `Signed in as ${user.name}` : "Please sign in"}</p>;
}&&: show something or nothing.
function Notices({ errors }: { errors: string[] }) {
return (
<div>
{errors.length > 0 && (
<ul role="alert">
{errors.map((e) => <li key={e}>{e}</li>)}
</ul>
)}
</div>
);
}Early return: for completely different output.
function OrderPage({ loading, error }: { loading: boolean; error?: string }) {
if (loading) return <p>Loading...</p>;
if (error) return <p role="alert">Error: {error}</p>;
return <p>Your orders</p>;
}Return null to render nothing at all.
The 0 && trap
React renders the number 0, but skips false, null and undefined.
{items.length && <List items={items} />}When the list is empty, items.length is 0, so 0 && ... returns 0, and the page shows a stray "0". Fix: make the condition a real boolean:
{items.length > 0 && <List items={items} />}A common interview "spot the bug" question.
Showing loading, error and success
Combine with a discriminated union (Lesson 107):
type LoadState<T> =
| { status: "loading" }
| { status: "error"; message: string }
| { status: "success"; data: T };
function ProductList({ state }: { state: LoadState<string[]> }) {
switch (state.status) {
case "loading":
return <p>Loading products...</p>;
case "error":
return <p role="alert">Could not load products: {state.message}</p>;
case "success":
return state.data.length === 0 ? (
<p>No products yet.</p>
) : (
<ul>{state.data.map((p) => <li key={p}>{p}</li>)}</ul>
);
}
}Always design the empty state too, not just loading, error and success.
How to say it in an interview
"I pass handler functions to props like onClick rather than calling them, using an arrow function when I need arguments. React gives a synthetic event, which I type, for example ChangeEvent of HTMLInputElement imported from react, and I call preventDefault on form submits. For conditional rendering I use ternaries, && with a real boolean to avoid rendering a stray 0, early returns, or null. I model loading, error, empty and success explicitly, often with a discriminated union."
Key words
| Word | Meaning |
|---|---|
| Event handler | A function that runs when an event happens |
| Synthetic event | React's wrapper around the browser's event |
| Conditional rendering | Showing different UI based on conditions |
| Early return | Returning different JSX before the main return |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.