In React, conditional rendering refers to the ability to render different UI components or elements based on specific conditions, much like conditional statements in JavaScript.
Conditional rendering makes React applications interactive and user-friendly by enabling the UI to show or hide elements, switch between components and update content dynamically.
What Is Conditional Rendering in React?
Conditional rendering is a method in React that determines which components or elements should be displayed based on a given condition. Instead of showing all elements at once, React allows developers to control what appears in the UI based on state, props or other logic.
For example, in a shopping cart, conditional rendering can display different buttons or messages based on whether the cart is empty or contains items. In a login form, it can display different content based on the user’s authentication status.
Basic Approaches to Conditional Rendering
React provides several approaches for implementing conditional rendering, each suited for different scenarios. Let’s go over each method:
a) Using if Statements
Using an if statement is one of the simplest ways to render content conditionally. This approach is commonly used within a function to decide what to render based on certain conditions.
Example: Rendering Based on User Authentication Status
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
} else {
return <GuestGreeting />;
}
}
// Usage
<Greeting isLoggedIn={true} />
In this example:
- UserGreeting and GuestGreeting are components displayed based on the isLoggedIn prop.
- If isLoggedIn is true, UserGreeting renders; otherwise, GuestGreeting renders.
b) Using Ternary Operators
Ternary operators provide a concise way to render content conditionally. This is particularly useful for inline conditions where only two outcomes are possible.
Example: Displaying a Button Based on Login Status
function LoginButton(props) {
return <button onClick={props.onClick}>Login</button>;
}
function LogoutButton(props) {
return <button onClick={props.onClick}>Logout</button>;
}
function AuthButton(props) {
const isLoggedIn = props.isLoggedIn;
return (
<div>
{isLoggedIn ? <LogoutButton onClick={props.handleLogout} /> : <LoginButton onClick={props.handleLogin} />}
</div>
);
}
// Usage
<AuthButton isLoggedIn={false} handleLogin={() => {}} handleLogout={() => {}} />
In this example:
- A ternary operator is used to choose between the LoginButton and LogoutButton based on the isLoggedIn prop.
c) Using Logicalc && Operator
For cases where a condition should display content only when true, you can use the logical && operator. This approach renders content when the condition is true and renders nothing when it’s false.
Example: Showing a Warning Message
function WarningBanner(props) {
if (!props.warn) {
return null; // Renders nothing if warn is false
}
return <div className="warning">Warning! Please proceed with caution.</div>;
}
function App() {
const [showWarning, setShowWarning] = useState(true);
return (
<div>
<WarningBanner warn={showWarning} />
<button onClick={() => setShowWarning(!showWarning)}>
{showWarning ? 'Hide' : 'Show'} Warning
</button>
</div>
);
}
// Usage
<App />
In this example:
- WarningBanner only displays if the warn prop is true.
- The && operator in WarningBanner ensures that nothing is rendered if warn is false.
d) Using switch Statements
In cases with multiple conditions, switch statements offer a structured way to handle conditional rendering. This approach is particularly useful when there are multiple outcomes.
Example: Choosing Different UI Based on User Role
function RoleMessage(props) {
const { role } = props;
switch (role) {
case 'admin':
return <p>Welcome, Admin! You have full access.</p>;
case 'editor':
return <p>Welcome, Editor! You can edit content.</p>;
case 'viewer':
return <p>Welcome, Viewer! You have read-only access.</p>;
default:
return <p>Unknown role. Please contact support.</p>;
}
}
// Usage
<RoleMessage role="admin" />
In this example:
- The RoleMessage component renders a different message based on the user’s role prop, leveraging the switch statement for clarity.
Using Conditional Rendering with JSX
In React, JSX expressions allow embedding JavaScript logic directly within the HTML-like syntax, enabling inline conditional rendering within the JSX. This approach is powerful for handling complex conditions within JSX.
Example: Conditional Class and Style Rendering
function Message(props) {
const { message, isImportant } = props;
return (
<div className={`message ${isImportant ? 'important' : ''}`}>
{message}
</div>
);
}
// Usage
<Message message="This is important!" isImportant={true} />
In this example:
- The className dynamically changes based on the isImportant prop, allowing conditional styling directly in JSX.
Conditional Rendering with && Operator in JSX
Using the && operator within JSX is an efficient way to conditionally render small UI elements, such as displaying an icon, label or message when a specific condition is met.
Example: Showing an Icon Conditionally
function UserStatus(props) {
return (
<div>
{props.isOnline && <span className="online-indicator">Online</span>}
</div>
);
}
// Usage
<UserStatus isOnline={true} />
In this example:
- If isOnline is true, the online-indicator span will render, showing the user is online.
Conditionally Rendering Multiple Elements
When rendering a list of components conditionally, Array.prototype.map() can be used to iterate over an array and conditionally render each item based on certain criteria.
Example: Displaying a List of Products Based on Availability
function ProductList(props) {
const products = props.products;
return (
<ul>
{products.map((product) =>
product.isAvailable ? <li key={product.id}>{product.name}</li> : null
)}
</ul>
);
}
// Usage
const products = [
{ id: 1, name: 'Product 1', isAvailable: true },
{ id: 2, name: 'Product 2', isAvailable: false },
];
<ProductList products={products} />
In this example:
- Each product’s availability is checked. If isAvailable is true, the product’s name is displayed; otherwise, it’s skipped.
Best Practices for Conditional Rendering
To ensure efficient and readable code, here are some best practices for conditional rendering in React:
- Keep It Simple: Use concise syntax like ternary operators or logical operators for simple conditions.
- Avoid Nested Conditions: Deeply nested conditions can make code harder to read. Use functions to abstract complex logic where necessary.
- Use Short-Circuit Evaluation (&&) for Small Conditions: For conditions that only affect the rendering of small elements or details, && short-circuit evaluation is effective.
- Avoid Inline if Conditions in JSX: Instead of writing if conditions directly in JSX, use ternary operators or conditional rendering helper functions for readability.