Conditional Rendering
In React, Conditional Rendering allows you to create different UI elements based on certain conditions or state. It works the same way conditions work in JavaScript.
1. Logical && Operator
The && operator is useful when you want to render something only if a condition is true, and nothing if it is false.
JavaScript
function Notification({ count }) {
return (
<div>
<h1>Dashboard</h1>
{count > 0 && <p>You have {count} new messages!</p>}
</div>
);
} 2. Ternary Operator (condition ? true : false)
The Ternary Operator is the most common way to conditionally render one of two elements.
JavaScript
function AuthStatus({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<button>Logout</button>
) : (
<button>Login</button>
)}
</div>
);
} 3. If Statements
You can use standard if or switch statements, but they must be placed outside the JSX return statement.
JavaScript
function LoadingButton({ isLoading }) {
if (isLoading) {
return <button disabled>Loading...</button>;
}
return <button>Click Me</button>;
} Note: Returning null from a component will prevent it from rendering anything to the screen.