Introduction
Conditional rendering is one of the most important concepts in React. It allows developers to render components, elements, or UI blocks dynamically based on conditions. In traditional programming, conditions control the flow of execution. In React, conditions control what appears on the screen.
Instead of always rendering everything, you can show or hide parts of the UI depending on user input, application state, or logic. For example:
- Showing a loading spinner until data is fetched.
- Displaying different components for logged-in and logged-out users.
- Rendering messages when certain conditions are met.
In this post, we will cover:
- Basics of conditional rendering.
- Different ways to implement conditional rendering in React.
- Using
ifstatements, ternary operators, and logical operators. - Rendering multiple conditions.
- Best practices for clean conditional rendering.
- Real-world examples.
- Performance considerations.
What is Conditional Rendering
Conditional rendering means that React decides which elements to render in the DOM based on a condition. The condition can be a state value, a prop, or a computed expression.
For example:
function Greeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign up.</h1>;
}
Here, the component returns different JSX depending on the value of props.isLoggedIn.
Why Conditional Rendering is Important
- Improves User Experience: Users only see relevant information.
- Reduces UI Clutter: Unnecessary elements do not appear.
- Handles Dynamic Scenarios: Loading states, error messages, or success notifications.
- Enables Reusability: Components adapt to different conditions without creating separate components.
Conditional Rendering Using if Statement
The most basic way to implement conditional rendering is with a standard if statement.
Example
function LoginStatus({ isLoggedIn }) {
if (isLoggedIn) {
return <p>You are logged in</p>;
} else {
return <p>You are not logged in</p>;
}
}
Explanation
- The function checks
isLoggedIn. - If true, it renders “You are logged in”.
- Otherwise, it renders “You are not logged in”.
This approach is simple but requires explicit branching.
Conditional Rendering Using Ternary Operator
The ternary operator (condition ? trueExpression : falseExpression) provides a concise way to render based on conditions.
Example
function UserGreeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in</h1>}
</div>
);
}
Benefits
- Shorter and more readable than
if-else. - Works directly inside JSX.
Conditional Rendering Using Logical AND Operator
Sometimes, you want to render something only if a condition is true, and render nothing otherwise. The logical AND (&&) operator is useful here.
Example
function Notifications({ messages }) {
return (
<div>
{messages.length > 0 && <h2>You have {messages.length} new messages</h2>}
</div>
);
}
Explanation
- If
messages.length > 0, the<h2>element renders. - If not, React renders nothing.
This prevents the need for writing an explicit else.
Conditional Rendering Using Switch Case
For multiple possible conditions, a switch statement or multiple if-else chains can be used.
Example
function StatusMessage({ status }) {
switch (status) {
case "loading":
return <p>Loading...</p>;
case "success":
return <p>Data loaded successfully!</p>;
case "error":
return <p>Something went wrong.</p>;
default:
return <p>Idle state.</p>;
}
}
This is useful when dealing with multiple states such as loading, error, and success.
Inline Conditional Rendering
Inline rendering means writing conditions directly in JSX without a separate block.
Example
function UserCard({ user }) {
return (
<div>
<h1>{user.name}</h1>
{user.isAdmin && <span>Admin</span>}
</div>
);
}
Here, the span element is rendered only if user.isAdmin is true.
Conditional Rendering with Functions
You can separate rendering logic into helper functions for clarity.
Example
function renderGreeting(isLoggedIn) {
if (isLoggedIn) {
return <h1>Hello, User!</h1>;
}
return <h1>Welcome, Guest!</h1>;
}
function Greeting({ isLoggedIn }) {
return <div>{renderGreeting(isLoggedIn)}</div>;
}
This approach helps when rendering logic is complex.
Nested Conditional Rendering
Sometimes, you may need multiple conditions inside one component.
Example
function UserDashboard({ user }) {
if (!user) {
return <p>Please log in.</p>;
} else if (user.role === "admin") {
return <p>Welcome Admin, {user.name}</p>;
} else {
return <p>Welcome {user.name}</p>;
}
}
Here, three conditions determine what message is displayed.
Conditional Rendering with Null
React allows returning null to render nothing.
Example
function WarningBanner({ showWarning }) {
if (!showWarning) {
return null;
}
return <div className="warning">Warning!</div>;
}
Returning null is useful for conditionally hiding UI.
Rendering Components Dynamically
Sometimes, you may want to render completely different components based on a condition.
Example
function AdminPanel() {
return <h1>Admin Dashboard</h1>;
}
function UserPanel() {
return <h1>User Dashboard</h1>;
}
function Dashboard({ isAdmin }) {
return (
<div>
{isAdmin ? <AdminPanel /> : <UserPanel />}
</div>
);
}
This makes the UI flexible and modular.
Handling Multiple Conditions in JSX
For complex conditions, you can use immediately-invoked functions or extracted components.
Example with IIFE
function ComplexComponent({ status }) {
return (
<div>
{(() => {
if (status === "loading") return <p>Loading...</p>;
if (status === "success") return <p>Success!</p>;
if (status === "error") return <p>Error occurred!</p>;
return <p>Idle</p>;
})()}
</div>
);
}
This keeps conditions inline without cluttering JSX.
Real-World Examples of Conditional Rendering
Example 1: Authentication
function Navbar({ isLoggedIn }) {
return (
<nav>
{isLoggedIn ? <button>Logout</button> : <button>Login</button>}
</nav>
);
}
Example 2: Loading Spinner
function DataFetcher({ isLoading, data }) {
if (isLoading) {
return <p>Loading...</p>;
}
return <div>{data}</div>;
}
Example 3: Form Validation
function FormError({ error }) {
return <>{error && <p className="error">{error}</p>}</>;
}
Best Practices for Conditional Rendering
- Keep JSX clean: Avoid deeply nested conditions in JSX.
- Extract functions: Move logic into helper functions when complex.
- Use ternaries wisely: Use them for short conditions only.
- Prefer readability over compactness: Clean code is better than short code.
- Avoid unnecessary rendering: Use
nullto skip rendering. - Modularize conditions: Break components into smaller ones.
Performance Considerations
- Conditional rendering can affect performance if heavy components are rendered unnecessarily.
- Use
React.memoto prevent re-renders when conditions do not change. - Avoid rendering large lists with heavy conditions inline.
- Use lazy loading for expensive components.
Common Mistakes
- Using multiple ternaries inline, making code unreadable.
- Forgetting to return
nullfor “render nothing” cases. - Mixing too much business logic with JSX.
- Over-complicating simple conditions.
Leave a Reply