Concept Flow - Conditional component rendering
Start Render
Evaluate Condition
Render Component A
Display Output
React checks a condition during rendering and shows one component or another based on that condition.
function Greeting({ isLoggedIn }) { return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>; }
| Step | isLoggedIn Value | Condition (isLoggedIn ?) | Component Rendered | Output Text |
|---|---|---|---|---|
| 1 | true | true | <h1>Welcome back!</h1> | Welcome back! |
| 2 | false | false | <h1>Please sign in.</h1> | Please sign in. |
| 3 | null | false | <h1>Please sign in.</h1> | Please sign in. |
| 4 | undefined | false | <h1>Please sign in.</h1> | Please sign in. |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| isLoggedIn | undefined | true | false | null | undefined |
Conditional component rendering in React: Use a condition inside the return to choose which component to show. Syntax example: return condition ? <A /> : <B />; If condition is true, render first component; else render second. Useful for showing different UI based on state or props.
condition ? exprIfTrue : exprIfFalse, which matches {condition ? <ComponentA /> : <ComponentB />}.isLoggedIn is false?
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
</div>
);
}function Message({ show }) {
return (
<div>
{show && <p>Hello World!</p> else <p>No message</p>}
</div>
);
}const notifications = [];
function NotificationList() {
return (
<div>
{/* Choose the correct conditional rendering here */}
{notifications.length > 0 ? (
notifications.map((note, index) => <p key={index}>{note}</p>)
) : (
<p>No notifications</p>
)}
</div>
);
}Pass the test and this pattern moves unknown