Clean • Professional
Conditional rendering in React allows you to dynamically display UI elements based on the state, props, or other conditions. Unlike static HTML, React components can decide what to render at runtime. This is essential for building interactive and dynamic web applications.
In real-world applications, you often want to show different UI elements based on:
React makes this easy with JSX and JavaScript expressions.
if Statements Outside JSXKey point: You cannot place if statements directly inside JSX. Instead, you define a variable, use if statements to assign JSX to it, and then render the variable.
Example – Basic if statement:
function Greeting({ isLoggedIn }) {
let message;
if (isLoggedIn) {
message = <h1>Welcome Back!</h1>;
} else {
message = <h1>Please Log In</h1>;
}
return <div>{message}</div>;
}
// Usage
<Greeting isLoggedIn={true} />
The ternary operator (condition ? true : false) allows inline conditional rendering directly in JSX.
Example – Inline conditional rendering:
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome Back!</h1> : <h1>Please Log In</h1>}
</div>
);
}
// Usage
<Greeting isLoggedIn={false} />
&&) OperatorThe logical AND operator is helpful when you want to render something only if a condition is true.
Example – Render element conditionally:
function Notifications({ count }) {
return (
<div>
{count > 0 && <p>You have {count} new notifications.</p>}
</div>
);
}
// Usage
<Notifications count={3} />
For complex conditions or multiple UI branches, helper functions keep JSX clean.
Example – Using a helper function:
function getGreeting(isLoggedIn) {
if (isLoggedIn) {
return <h1>Welcome Back!</h1>;
}
return <h1>Please Log In</h1>;
}
function App() {
const userLoggedIn = true;
return <div>{getGreeting(userLoggedIn)}</div>;
}
For multiple states (like loading, success, error), you can chain if-else statements:
function StatusMessage({ status }) {
let message;
if (status === "loading") {
message = <p>Loading...</p>;
} else if (status === "success") {
message = <p>Data Loaded Successfully!</p>;
} else if (status === "error") {
message = <p>Error Occurred!</p>;
} else {
message = <p>Unknown status</p>;
}
return <div>{message}</div>;
}
// Usage
<StatusMessage status="success" />