- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React Conditional Rendering
- Conditional rendering in React involves displaying different components or content based on certain conditions, such as user authentication, data loading states, or toggle switches.
- It allows you to create dynamic and responsive user interfaces that adapt to user interactions and data changes in real-time.
In React, conditional rendering works the same way conditions work in JavaScript. You use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.
Using the Ternary Operator
The ternary operator (condition ? true : false) is a concise way to conditionally render content directly inside your JSX. It is best used when you have two mutually exclusive options (an "either/or" scenario).
import React, { useState } from 'react';
const ConditionalRendering = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{/* If true, show Welcome. If false, show Login button */}
{isLoggedIn ? (
<div>
<p>Welcome back, power user!</p>
<button onClick={() => setIsLoggedIn(false)}>Log Out</button>
</div>
) : (
<div>
<p>Please log in to continue.</p>
<button onClick={() => setIsLoggedIn(true)}>Log In</button>
</div>
)}
</div>
);
};
if statement or a switch instead.
Using Logical && Operator
The && operator is perfect for "short-circuit" evaluation. Use this when you want to render a component only if a condition is true, and render nothing if it is false.
import React, { useState } from 'react';
const ConditionalRenderingLogical = () => {
const [unreadMessages, setUnreadMessages] = useState(['Hello!', 'Meeting at 5?']);
return (
<div>
<h1>Inbox</h1>
{/* The message only renders if there are items in the array */}
{unreadMessages.length > 0 && (
<p>You have {unreadMessages.length} unread messages.</p>
)}
</div>
);
};
0 in your UI if the left side of your && expression is the number zero. To avoid this, ensure the condition is a boolean, like unreadMessages.length > 0 && ... instead of just unreadMessages.length && ....
Using if Statements
While you can't use if statements directly inside a JSX return block (because JSX is syntactic sugar for function calls), you can use them in the surrounding JavaScript logic to assign components to variables or to handle early returns.
import React, { useState } from 'react';
const ConditionalRenderingIfStatement = ({ isLoading }) => {
const [isSpecial, setIsSpecial] = useState(true);
// 1. Early Return Pattern (Great for Loading/Error states)
if (isLoading) {
return <p>Fetching data from server...</p>;
}
// 2. Variable Assignment Pattern
let statusMessage;
if (isSpecial) {
statusMessage = <p>✨ This is a premium special feature!</p>;
} else {
statusMessage = <p>This is a standard feature.</p>;
}
return (
<div className="container">
<h2>Dashboard</h2>
{statusMessage}
</div>
);
};
Switch Statement for Multiple Conditions
A switch statement is ideal when you have multiple distinct states or roles, such as different UI layouts for "Guest", "User", "Editor", and "Admin".
import React, { useState } from 'react';
const ConditionalRenderingSwitch = () => {
const [userRole, setUserRole] = useState('editor');
const renderContent = () => {
switch (userRole) {
case 'admin':
return <p>Settings: Full System Access</p>;
case 'editor':
return <p>Settings: Edit and Publish content</p>;
case 'user':
return <p>Settings: View Profile and Comments</p>;
default:
return <p>Please log in to see your permissions.</p>;
}
};
return (
<div className="role-panel">
<strong>Current Role: {userRole}</strong>
{renderContent()}
</div>
);
};
renderContent above). This keeps your main return block easy to scan.
Summary
Understanding and using conditional rendering in React is essential for creating dynamic and user-friendly interfaces. By mastering the ternary operator for simple toggles, the logical && for optional elements, and if/switch statements for complex logic, you gain full control over the user experience. Always prioritize readability if your JSX looks messy, it’s probably time to move that logic into a variable or a helper function.