JSX Conditionals
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.
1. Why Conditional Rendering Is Important
In real-world applications, you often want to show different UI elements based on:
- User authentication: Display login form or dashboard depending on login status.
- Loading states: Show a spinner while data is loading.
- Error handling: Display error messages when something goes wrong.
- Dynamic content: Render content based on user selections or API responses.
React makes this easy with JSX and JavaScript expressions.
2. Using if Statements Outside JSX
Key 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} />
3. Using the Ternary Operator Inside JSX
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} />
4. Using Logical AND (&&) Operator
The 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} />
5. Using Helper Functions for Conditional Rendering
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>;
}
6. Handling Multiple Conditions
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" />
