Skip to main content

Showing the right thing at the right time

React apps constantly need to show different UI based on conditions: a spinner while loading, an error message if something failed, a login button if the user isn’t authenticated. This is conditional rendering. You already know the JavaScript for this — ternary operators, &&, and if/else from the conditionals lesson. In React, you use the same patterns inside JSX.

&& — show something or nothing

The most common pattern. Show an element if a condition is true, nothing if false:
&& is perfect when you want to either show something or show nothing. If the left side is truthy, the right side renders. If falsy, nothing renders.
Watch out for 0 && <Component />. Because 0 is falsy, React renders the number 0 on the page instead of nothing. Use count > 0 && <Component /> instead of count && <Component />.

Ternary — show one thing or another

When you need to choose between two different outputs:
Use && when you have a show/hide situation. Use ternary when you have an either/or situation. Keep ternaries simple — if the logic gets complex, extract it to a variable or use early returns.

Early returns — the cleanest pattern

For loading, error, and empty states, use early returns at the top of your component:
This is the standard pattern for data-fetching components. Check states in order of priority: loading → error → empty → data.

The loading / error / data pattern

You’ll write this in almost every component that fetches data:

Conditional CSS classes

For complex class logic, consider a utility like clsx or classnames: className={clsx("btn", isPrimary && "btn-primary", isLarge && "btn-lg")}. It’s cleaner than manual string concatenation.

Conditional rendering with variables

For more complex conditions, compute the JSX before the return:
Or with an object lookup (cleaner for many cases):

Preventing rendering with null

Return null to render nothing:

What’s next?

You can show and hide UI based on conditions. Now let’s learn how to render lists of data — the most common thing you’ll do with API responses.

List rendering

Render arrays of data as lists of components