What is conditional rendering?
- React course
- Beginner
- Lesson 22/84
- 4 min
Learn that you can show different content based on a condition.
What is conditional rendering?
Conditional rendering shows different content based on a condition. For example, showing Dashboard when the user is logged in and Login when not.
React offers several ways: the if statement, the ternary operator cond ? a : b, the logical AND &&, and early return. Each fits a different situation.
The rule: the value returned by the condition is either valid JSX or null, false, undefined (React renders none of these).
Conditional render approaches
Three common approaches exist. First, ternary: { 'isLoggedIn ? <Dashboard /> : <Login />' }. Ideal for choosing between two options.
Second, logical AND: { 'hasError && <Error />' }. Ideal for showing something only when a condition holds.
Third, early return: at the top of the component, if (!user) return null;. Improves readability for complex conditions.
Practice Banner by login state
Complete the skeleton. Write a component called Banner that takes ({ '{ isLoggedIn }' }) as parameter. If isLoggedIn is true, return <p>Welcome</p>; otherwise <p>Please log in</p> (use ternary). Don't forget to export.
Starter code
// Write the Banner component hereSample solution
function Banner({ isLoggedIn }) {
return isLoggedIn ? <p>Welcome</p> : <p>Please log in</p>;
}
export default Banner;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does conditional rendering do?
- Shows different content based on a condition Correct answer
- Changes styling
- Stores state
- Updates DOM
Explanation: Conditional rendering shows content based on a condition.
2 Conditional render syntax
Condition ____ ? a : b.
Condition ? ? a : b.
Explanation: ? is the ternary operator.
3 Match the approaches
| Term | Meaning |
|---|---|
cond ? a : b |
Ternary |
cond && a |
Logical AND |
if (x) return |
Early return |
null |
Not rendered |