React is all about building dynamic interfaces — and conditional rendering is one of the most important tools in your toolkit. Whether you're showing a user profile after login or a spinner while data is loading, knowing when and how to render content conditionally is key.
In this post, we'll delve into how to use two of the most common conditional rendering techniques in React: the logical AND (&&
) operator and the ternary operator (? :
) — with examples, best practices, and a few mistakes to avoid.
🔹 What Is Conditional Rendering?
Conditional rendering in React lets you control what is displayed in the UI based on component state or props.
Think of it as the “if” of your component view:
{isLoggedIn && <p>Welcome back!</p>}
{items.length === 0 ? <p>No items</p> : <ul>{items.map(...)} </ul>}
✅ Using Logical AND (&&
)
The logical AND
operator is great when you only want to show something if a condition is true or met.
🧩 Example
{isLoggedIn && <h2>Welcome, user!</h2>}
If `isLoggedIn` is `true`, it renders the `<h2>`.
If `false`, it renders nothing.
⚠️ Beware of Falsy Values Like 0
{items.length && <p>{items.length} items</p>} // Renders 0!
Use !!items.length
to coerce to a boolean:
{!!items.length && <p>{items.length} items</p>}
✅ Using the Ternary Operator (? :
)
Use the ternary operator when you want to display one of two UI blocks.
🧩 Example
{isLoggedIn ? <Dashboard /> : <Login />}
Or inline:
<button>{isLoading ? 'Loading...' : 'Submit'}</button>
💡 Best Practices
1.Prefer Early Returns
Instead of deeply nested ternaries:
return (
<div>
{user
? user.isAdmin
? <AdminPanel />
: <UserPanel />
: <Login />}
</div>
)
Use early returns:
if (!user) return <Login />;
if (user.isAdmin) return <AdminPanel />;
return <UserPanel />;
2.Extract Conditions to Variables
It improves clarity:
const showGreeting = isLoggedIn && user?.name;
return showGreeting ? <h1>Hello, {user.name}</h1> : null;
❗ Common Pitfalls
- Avoid rendering raw values like
false
,0
, orundefined
. - Avoid deeply nested ternaries — extract logic to helpers.
- Understand
_truthy_
and_falsy_
and their usage in JavaScript.
🚀 Final Thoughts
Conditional rendering is one of the most powerful features in React. By mastering &&
and ? :
, you can craft responsive, intuitive interfaces adaptable to user behaviour and application state.
✨ Want More?
Top comments (0)