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 &&.
Theory in plain words
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
The ternary operator
&& for "show or nothing"
Remember: write unread > 0, not just unread. A plain 0 would be shown on the screen.
Loading, error, success
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"?
condition && <X /> renders X when true and nothing when false.
2. What does a component show when it returns null?
null renders nothing.
3. Can you write an if statement inside JSX curly braces?
Use a ternary, or compute a variable before the return.
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.