Conditional rendering
if, ternaries, && and early returns — showing the right UI for each state.
Real interfaces change depending on the situation: show a spinner while loading, an error if something failed, a "log in" button for guests and an avatar for members, an empty-state message when a list has no items. In React, conditional rendering is just JavaScript — if, &&, ? : — applied to JSX.
if statements and early returns#
Because a component is a function, you can return different JSX from different branches:
Early returns are the clearest pattern for states that change the whole component:
Each case is handled at the top; the "happy path" JSX at the bottom doesn't have to worry about missing data.
Hooks must still run in the same order every render, so put all your
useState/useEffectcalls above any earlyreturn.
Rendering nothing: null#
Returning null means "render nothing". The parent can always render <Banner message={msg} /> without checking first.
The ternary operator ? :#
For "this or that" inside JSX, use the conditional operator:
Ternaries work anywhere an expression does: in text, attributes and class names.
Logical &&: "this or nothing"#
condition && <JSX /> renders the JSX only when the condition is truthy:
The 0 trap
React renders numbers, including 0:
Make the left side of && a boolean: count > 0, Boolean(value), !!value, or list.length !== 0.
Storing JSX in variables#
For more complex logic, compute a piece of JSX before the return:
This keeps the JSX skeleton tidy and the logic in plain if/else.
Choosing from many options: lookup objects and switch#
Avoid nested ternaries#
Move this into early returns, a switch, or a small component.
Showing and hiding: conditional rendering vs CSS#
There are two ways to "hide" something:
- Conditional rendering (
open && ...) unmounts the element. Any state inside it (like text typed into an input) is lost when it disappears. hidden/ CSS keeps it mounted, preserving state and avoiding re-creating expensive content — useful for tabs.
A complete example: a toggle panel#
Only one answer is open at a time because a single openId state controls them all. aria-expanded tells screen readers whether each question is open.
Common mistakes#
{count && <X />}rendering0.- Putting hooks after an early return.
- Deeply nested ternaries.
- Forgetting that conditionally-rendered components lose their state when hidden.
- Using
ifinside JSX braces — it's a statement; use a ternary or compute beforereturn.
What's next#
Next: rendering lists with map and choosing good keys — plus your first look at effects.
Check your understanding
Quick quiz
1.What does
{count && <Badge />}render whencountis0?2.What should a component return to render nothing?
3.Which is the clearest way to choose between three or more different UIs, like loading/error/success?
Finished reading?
Mark this lesson complete to track your progress.