React - Conditional Rendering
Conditional Rendering
Use JavaScript expressions to decide what to render.
Try it: Login Gate
View source
const { useState } = React;
function LoginGate(){
const [user, setUser] = useState(null);
return (
<div>
{user ? (
<>
<p>Welcome, {user.name}!</p>
<button onClick={() => setUser(null)}>Logout</button>
</>
) : (
<button onClick={() => setUser({ name: 'Ada' })}>Login</button>
)}
</div>
);
}
ReactDOM.createRoot(document.getElementById('try-conditional')).render(<LoginGate />);
Syntax primer (for newcomers)
- Ternary:
condition ? A : B
to choose between elements. - Logical AND:
condition && <SomeComponent />
to show something only when true. - Fragments:
<>...</>
group multiple elements without extra DOM.
Vocabulary
- Ternary:
cond ? A : B
expression choosing between two values. - Logical AND:
cond && value
renders the right-hand side only if cond is true.
Checks for Understanding
- What are two common patterns for conditional UI in React?
- When do fragments help with conditional rendering?
Show answers
- Ternaries (
cond ? A : B
) and logical AND (cond && <X />
). - When you need to return multiple sibling elements without adding an extra wrapper node.
Exercises
- Show a dismissible alert box only when a checkbox is checked.
- Render a list with an empty-state message using a ternary.
- Add a simulated loading state (e.g., 800ms) that shows a spinner before content.