Home / Learn React / Conditional Rendering

Conditional Rendering

Show different things depending on the data: a login button or a profile, a loader or a list. In React you use plain JavaScript: if, ? : and &&.

In shortUse if or the ternary operator to choose what to return. Use && to show something only when a condition is true.

Theory in plain words

A condition picks the outputstate or propscondition?JSX for yesJSX for no
A condition picks the output

What it is

Conditional rendering means the JSX your component returns depends on a condition. There is no special React syntax for it: you use normal JavaScript.

Why we use it

Real screens change with the situation: logged in or out, loading or loaded, empty list or full list, error or success.

How it works

On each render your component runs from the top. Whatever expression decides the result is evaluated again with the latest state and props, and React shows the new result. Returning null (or false) shows nothing.

Where it is used

  • Login and logout buttons
  • Loading spinners and error messages
  • Empty states ("No items yet")
  • Showing or hiding a menu, modal or panel

if with an early return

Early returnTry it Yourself

The ternary operator

condition ? yes : noTry it Yourself

&& for "show or nothing"

Show only when trueTry it Yourself

Remember: write unread > 0, not just unread. A plain 0 would be shown on the screen.

Loading, error, success

Three statesTry it Yourself
Tip:If you nest ternaries more than one level, move the logic into a variable or a small component. It is easier to read.
Careful:Do not use if inside the JSX curly braces. It is a statement, not an expression. Use a ternary or compute a variable before the return.

Quick quiz

1. Which operator is best for "show this or nothing"?

2. What does a component show when it returns null?

3. Can you write an if statement inside JSX curly braces?

Common questions

Which operator is best for "show this or nothing"?

&&. condition && <X /> renders X when true and nothing when false.

What does a component show when it returns null?

Nothing. null renders nothing.

Can you write an if statement inside JSX curly braces?

No, only expressions are allowed. Use a ternary, or compute a variable before the return.