REACT
React Conditional Rendering: Syntax, Usage, and Examples
React conditional rendering lets you control what appears in the UI based on state, props, or logic. Instead of rendering everything all the time, you can conditionally display components, elements, or text based on certain conditions.
How to Use Conditional Rendering in React
Conditional rendering in React can be implemented in multiple ways, including if-else statements, the ternary operator, and logical operators.
If-Else Conditional Rendering
If-else statements let you conditionally return different JSX elements.
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please log in.</h1>;
}
}
Ternary Operator
The ternary operator is a concise way to handle conditional rendering inside JSX.
function Greeting({ isLoggedIn }) {
return <h1>{isLoggedIn ? "Welcome back!" : "Please log in."}</h1>;
}
Logical AND (&&
)
The logical AND (&&
) operator renders an element only when a condition is true.
function Alert({ hasError }) {
return <>{hasError && <p>Error: Something went wrong.</p>}</>;
}
When to Use Conditional Rendering in React
Conditional rendering helps manage UI behavior dynamically. Use it when:
Displaying UI Based on Authentication
You can show different components depending on whether a user is logged in.
function AuthButton({ isAuthenticated }) {
return isAuthenticated ? <button>Logout</button> : <button>Login</button>;
}
Handling Empty or Loading States
Instead of displaying empty content, you can render placeholders or loading indicators.
function DataDisplay({ data }) {
if (!data) {
return <p>Loading...</p>;
}
return <p>Data: {data}</p>;
}
Toggling Features or UI Components
Certain UI components should only appear when specific conditions are met.
function Notifications({ showNotifications }) {
return (
<div>
{showNotifications && <p>You have new messages!</p>}
</div>
);
}
Examples of Conditional Rendering in React
Conditional Component Rendering
You can render different components based on a condition.
function UserGreeting() {
return <h1>Welcome, User!</h1>;
}
function GuestGreeting() {
return <h1>Welcome, Guest!</h1>;
}
function Greeting({ isLoggedIn }) {
return isLoggedIn ? <UserGreeting /> : <GuestGreeting />;
}
Inline Conditional Rendering
For simple conditions, you can inline the logic inside JSX.
function Status({ online }) {
return <p>Status: {online ? "Online" : "Offline"}</p>;
}
Multiple Conditional Rendering
You can chain multiple conditions to determine what to render.
function UserStatus({ user }) {
return (
<>
{user.isAdmin ? (
<p>Admin Access</p>
) : user.isMember ? (
<p>Member Access</p>
) : (
<p>Guest Access</p>
)}
</>
);
}
Learn More About Conditional Rendering in React
Conditional Component Rendering React
Instead of conditionally showing elements, you can dynamically render entire components. This is useful when switching between different UI layouts.
function Dashboard() {
return <h1>Admin Dashboard</h1>;
}
function Home() {
return <h1>User Home</h1>;
}
function App({ isAdmin }) {
return isAdmin ? <Dashboard /> : <Home />;
}
If-Else Conditional Rendering React
Using a function to return JSX based on an if-else condition can keep code clean.
function UserGreeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Hello, User!</h1>;
}
return <h1>Please sign in.</h1>;
}
Inline Conditional Rendering React
Inline rendering helps reduce extra lines of code when conditions are simple.
function ShoppingCart({ items }) {
return <p>{items.length > 0 ? `You have ${items.length} items` : "Cart is empty"}</p>;
}
React Animate Conditional Rendering
When conditionally rendering elements, animations help improve the UI experience.
import { useState } from "react";
import { CSSTransition } from "react-transition-group";
function AnimatedAlert({ show }) {
return (
<CSSTransition in={show} timeout={300} classNames="fade" unmountOnExit>
<p className="alert">Warning: Action required!</p>
</CSSTransition>
);
}
Multiple Conditional Rendering React
Combining different conditions allows complex UI logic without unnecessary nesting.
function SubscriptionMessage({ status }) {
return (
<p>
{status === "active"
? "Your subscription is active."
: status === "expired"
? "Your subscription has expired."
: "You don't have a subscription."}
</p>
);
}
React conditional rendering helps control what appears in the UI based on different factors like user authentication, data availability, or component state. By using techniques like if-else statements, the ternary operator, and logical operators, you can manage the display of UI elements.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.