Why Conditional Rendering?
Not everything should be on the screen all the time. Maybe a button only shows when a user is logged in. Maybe an error message appears only when something goes wrong. Conditional rendering lets you show or hide parts of your UI based on conditions.
React lets you use plain JavaScript to decide what to render. You're not limited to templates or special syntax โ you just write JavaScript. It's one of the things that makes React feel so natural.
If/Else Statements
The most straightforward way to do conditional rendering is with if/else. You check a condition, and if it's true, render one thing. If it's false, render another. Simple and readable.
You can use if/else directly inside your component or extract the logic into a helper function. Either way, it's just JavaScript doing what JavaScript does best.
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign in.</h1>;
}
function App() {
return <Greeting isLoggedIn={true} />;
}
Try it Yourself โ
Ternary Operator and Logical AND
For simpler conditions, the ternary operator is a compact way to render one of two things. It's like a mini if/else on a single line. Use it when the logic is straightforward and won't clutter your JSX.
When you only need to render something conditionally (or nothing at all), use the logical AND operator. If the condition is true, the second part renders. If it's false, React ignores it. It's perfect for showing or hiding elements.
function UserStatus({ isLoggedIn, username }) {
return (
<div>
{isLoggedIn ? (
<h1>Welcome, {username}!</h1>
) : (
<h1>Please sign in.</h1>
)}
{isLoggedIn && <p>Your dashboard is ready.</p>}
</div>
);
}
Try it Yourself โ