Conditional Rendering in React: Beginner’s Guide with Examples
In React, UI often needs to change dynamically based on certain conditions:
Show a login button if the user is logged out.
Show a logout button if the user is logged in.
Display loading messages while fetching data.
This is called Conditional Rendering. It lets your components decide what to render depending on the state or props.
Think of it as telling React: “If this happens, show this. Otherwise, show that.”
Method 1: Using if/else
The simplest way to handle conditions is using if/else statements inside a component.
function Greeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please log in.</h1>;
}
}
// Usage
<Greeting isLoggedIn={true} />
React chooses which element to render based on the condition.
Method 2: Using Ternary Operator
For inline conditions, the ternary operator is concise and readable:
function Greeting(props) {
return <h1>{props.isLoggedIn ? "Welcome back!" : "Please log in."}</h1>;
}
Useful for short conditions inside JSX.
Method 3: Using Logical AND (&&)
If you only want to render something when a condition is true, use &&.
function Notification(props) {
return (
<div>
<h2>Dashboard</h2>
{props.hasMessage && <p>You have new messages!</p>}
</div>
);
}
hasMessageistrue→ message is shownfalse→ nothing is rendered
Method 4: Using Switch Case
When there are multiple conditions, switch is cleaner than multiple if/else statements.
function StatusMessage({ status }) {
switch (status) {
case "loading":
return <p>Loading...</p>;
case "success":
return <p>Data loaded successfully!</p>;
case "error":
return <p>Something went wrong.</p>;
default:
return <p>Idle</p>;
}
}
Example: Login/Logout System
import { useState } from "react";
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? (
<div>
<h1>Welcome back!</h1>
<button onClick={() => setIsLoggedIn(false)}>Logout</button>
</div>
) : (
<div>
<h1>Please log in.</h1>
<button onClick={() => setIsLoggedIn(true)}>Login</button>
</div>
)}
</div>
);
}
User clicks Login/Logout, UI updates automatically.
Combines state + conditional rendering.
Best Practices
Use if/else for readability with complex conditions.
Use ternary operator for short, inline conditions.
Use logical
&&to render only if true.Use switch for multiple discrete conditions.
Avoid putting too much logic directly inside JSX — keep it clean.
FAQ
Q1: Can I return null in React render?
Yes. Returning null means render nothing.
Q2: Which method should I use?
Ternary for short conditions, if/else for complex logic, switch for multiple cases.
Q3: Can conditional rendering be combined with lists?
Yes. You can render a filtered list conditionally using .map() and conditions.