Concept Flow - Why conditional rendering is needed
Start Component Render
Evaluate Condition
Render JSX A
Display Output on Screen
The component checks a condition during render. If true, it shows one UI; if false, it shows another or nothing.
function Greeting({ isLoggedIn }) { return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} </div> ); }
| Step | isLoggedIn Value | Condition (isLoggedIn ?) | Rendered JSX | Output Displayed |
|---|---|---|---|---|
| 1 | true | true | <h1>Welcome back!</h1> | Welcome back! |
| 2 | false | false | <h1>Please sign in.</h1> | Please sign in. |
| Variable | Start | After Step 1 | After Step 2 |
|---|---|---|---|
| isLoggedIn | undefined | true | false |
Conditional rendering in React lets components show different UI based on data. Use a condition inside JSX with ? : to choose what to display. This helps create dynamic, user-friendly interfaces. Without it, UI would be static and less useful.
{condition && <Component />} renders the component only if condition is true.{condition && <Component />} matches the correct syntax exactly. {condition && &<Component />} has an extra & symbol. {condition ? <Component /> : null} uses ternary, which is correct but not && syntax. {condition ? <Component />} is incomplete ternary syntax.function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);
}isLoggedIn is false?isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>. If isLoggedIn is true, it shows "Welcome back!"; otherwise, it shows "Please sign in."false to the conditionisLoggedIn is false, the component renders the second part: <h1>Please sign in.</h1>.function ShowMessage({ show }) {
return (
<div>
{show ? <p>Hello!</p>}
</div>
);
}{show ? <p>Hello!</p>} which is incomplete because ternary requires both true and false parts separated by a colon.{show ? <p>Hello!</p> : null} or another expression after colon.isLoggedIn and isAdmin are true.{isLoggedIn && isAdmin && <AdminMessage />} uses isLoggedIn && isAdmin && <AdminMessage />, which renders the message only if both are true. {isLoggedIn ? <AdminMessage /> : <LoginPrompt />} shows message if logged in regardless of admin. {isAdmin ? <AdminMessage /> : null} ignores logged-in status. {isLoggedIn || isAdmin ? <AdminMessage /> : null} uses OR, showing message if either is true, which is incorrect.Pass the test and this pattern moves unknown