Conditional Rendering
Conditional rendering shows different content for different conditions. A condition is a true or false check.
A variable holds JSX
The variable holds the greeting that matches the condition.
const loggedIn = true;
let message;
if (loggedIn) { message = <p>Welcome back.</p>; }
else { message = <p>Please log in.</p>; }
return message;An early return
The return sends back the login message at once.
const loggedIn = false;
if (!loggedIn) { return <p>Please log in.</p>; }
return <p>Welcome back.</p>;Example
import { useState } from 'react';
export default function App() {
const [loggedIn, setLoggedIn] = useState(false);
if (!loggedIn) {
return (
<div>
<p>Please log in.</p>
<button onClick={() => setLoggedIn(true)}>Log in</button>
</div>
);
}
return (
<div>
<p>Welcome back.</p>
<button onClick={() => setLoggedIn(false)}>Log out</button>
</div>
);
}
Key points
- An if statement chooses one branch of code.
- A variable can hold one piece of JSX or another.
- The component returns the variable as its output.
- An early return sends back JSX before the rest of the code runs.
- Only one branch renders at a time.
In this example, the loggedIn state value starts as false. The early return sends back the login message and the Log in button. A click sets loggedIn to true. The next render skips the early return and shows the welcome message. The Log out button sets loggedIn back to false.
Note
The condition runs on every render, so the display stays in step with state.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does conditional rendering do?