Conditional rendering in React is the display of different elements or components based on certain conditions. React allows you to use standard JavaScript expressions and operators to control what appears on the screen.
Main conditional rendering approaches:
if/else
statements? :
&&
null
Example with ternary operator:
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn
? <h1>Welcome back!</h1>
: <h1>Please sign in</h1>
}
</div>
);
}
Conditional rendering is a powerful pattern in React that allows displaying different components or elements depending on the application state. It’s one of the fundamental concepts for creating dynamic interfaces. 🧩
The classic approach using if/else
to determine what to render:
function UserStatus({ isLoggedIn }) {
if (isLoggedIn) {
return <div>User is logged in</div>;
} else {
return <div>User is not logged in</div>;
}
}
A concise way to embed conditional logic directly in JSX:
function Button({ isActive }) {
return (
<button className={isActive ? 'active' : 'inactive'}>
{isActive ? 'Active Button' : 'Inactive Button'}
</button>
);
}
A convenient way for conditional rendering of a single element:
function Notification({ hasMessages }) {
return (
<div>
{hasMessages && <span>You have unread messages</span>}
</div>
);
}
To completely hide a component, you can return null
:
function AdminPanel({ isAdmin }) {
if (!isAdmin) {
return null;
}
return <div>Admin Panel</div>;
}
A more flexible approach using variables:
function LoginControl({ isLoggedIn }) {
let button;
if (isLoggedIn) {
button = <LogoutButton />;
} else {
button = <LoginButton />;
}
return (
<div>
<div>Status: {isLoggedIn ? 'Online' : 'Offline'}</div>
{button}
</div>
);
}
Method | Advantages | Disadvantages |
---|---|---|
if/else | Simple and clear | Verbose for simple conditions |
Ternary operator | Compact, integrates with JSX | Can become hard to read when nested |
&& operator | Very concise for simple conditions | Only works for a single variant |
Returning null | Completely hides component | Doesn’t show an alternative |
Variables | Flexible and readable | Requires additional code |
// ❌ Problematic code
function Counter({ count }) {
return (
<div>
{count && <h1>Count: {count}</h1>}
</div>
);
}
// If count = 0, it will display "0" instead of the heading!
Solution:
// ✅ Correct
function Counter({ count }) {
return (
<div>
{count > 0 && <h1>Count: {count}</h1>}
</div>
);
}
// ❌ Hard to read
function Component({ isAuth, isAdmin, hasPermission }) {
return (
<div>
{isAuth && isAdmin ?
hasPermission ? <AdminPanel /> : <NoPermission />
: <LoginForm />}
</div>
);
}
Solution:
// ✅ Better to use a variable
function Component({ isAuth, isAdmin, hasPermission }) {
let content;
if (!isAuth) {
content = <LoginForm />;
} else if (isAdmin && hasPermission) {
content = <AdminPanel />;
} else {
content = <NoPermission />;
}
return <div>{content}</div>;
}
For complex components, early returns can improve readability:
function ProfilePage({ user, isLoading, error }) {
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage message={error} />;
if (!user) return <NotFound />;
return <UserProfile user={user} />;
}
Conditional rendering can lead to unnecessary re-renders:
// ❌ Component always re-renders
function Dashboard({ user }) {
const [activeTab, setActiveTab] = useState('overview');
return (
<div>
<Tabs activeTab={activeTab} onChange={setActiveTab} />
{activeTab === 'overview' && <Overview user={user} />}
{activeTab === 'settings' && <Settings user={user} />}
{activeTab === 'profile' && <Profile user={user} />}
</div>
);
}
Solution:
// ✅ Object to store components
function Dashboard({ user }) {
const [activeTab, setActiveTab] = useState('overview');
const tabs = {
overview: <Overview user={user} />,
settings: <Settings user={user} />,
profile: <Profile user={user} />
};
return (
<div>
<Tabs activeTab={activeTab} onChange={setActiveTab} />
{tabs[activeTab]}
</div>
);
}
✅ Conditional Rendering in React:
✅ Recommendations:
Proper use of conditional rendering helps create dynamic and adaptive user interfaces that respond to user actions and data changes. 🚀
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site, and improve yourself every day 💪