Conditional Rendering
Why Conditional Rendering?
We often need to display different UI elements depending on a certain condition, such as login status, user role, or a loading result.
Using if/else
The most basic approach: use if/else inside the component.
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please log in.</h1>;
}
Using the Ternary Operator
The ternary is ideal for simple conditions inside JSX.
function Status({ online }) {
return (
<div>
<p>Current user:</p>
{online ? (
<span className="status-green">Online</span>
) : (
<span className="status-red">Offline</span>
)}
</div>
);
}
Using the && Operator
Use && if you only want to render something when the condition is true.
function Notification({ count }) {
return (
<div>
<h2>Messages</h2>
{count > 0 && (
<span className="badge">{count} new messages</span>
)}
</div>
);
}
Note: Avoid && with a number on the left side. {count && <span>...</span>} will render 0 if count is 0.
If Statements Outside the Return
For complex logic, place the if statements outside the return.
function Dashboard({ user }) {
let content;
if (!user) {
content = <p>You are not logged in.</p>;
} else if (user.role === "admin") {
content = <AdminPanel user={user} />;
} else {
content = <UserPanel user={user} />;
}
return (
<div className="dashboard">
<h1>Dashboard</h1>
{content}
</div>
);
}
Rendering null or false
Returning null from a component makes React render nothing.
function Sidebar({ showSidebar }) {
if (!showSidebar) {
return null;
}
return (
<aside className="sidebar">
<nav>
<a href="#home">Home</a>
<a href="#profile">Profile</a>
<a href="#settings">Settings</a>
</nav>
</aside>
);
}
Example: Logged In / Not Logged In
import { useState } from 'react';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [name, setName] = useState("");
const login = () => {
setName("John");
setIsLoggedIn(true);
};
const logout = () => {
setName("");
setIsLoggedIn(false);
};
return (
<div>
<h1>Application</h1>
{isLoggedIn ? (
<div>
<p>Welcome, {name}!</p>
<button onClick={logout}>Log Out</button>
</div>
) : (
<div>
<p>Please log in to continue.</p>
<button onClick={login}>Log In</button>
</div>
)}
</div>
);
}
export default App;
Summary
Conditional rendering lets you display different UIs depending on a condition. Choose the method that fits: if/else for complex logic, the ternary for inline conditions, and && for render-if-true.
The next chapter covers Lists & Keys — how to render lists of data dynamically from an array.