How to conditionally render elements in React
Conditional rendering is essential for creating dynamic React applications that show different content based on state, props, or user interactions. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented conditional rendering in thousands of React components for error states, loading indicators, user permissions, and responsive layouts in enterprise applications. From my expertise, the most versatile approach is to use logical operators and ternary expressions within JSX. This method provides clean, readable code while supporting complex conditional logic and optimal performance through React’s virtual DOM reconciliation.
Use logical operators &&
and ternary expressions ? :
for conditional rendering in JSX.
function UserProfile({ user, isLoading, error }) {
return (
<div>
{isLoading && <div>Loading...</div>}
{error && <div className="error">{error.message}</div>}
{user ? (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
) : (
<div>No user data available</div>
)}
</div>
)
}
React supports conditional rendering using JavaScript expressions within JSX. The logical AND operator &&
renders the element only when the condition is truthy: {isLoading && <div>Loading...</div>}
. Ternary operators ? :
provide if-else logic: {user ? <UserCard /> : <EmptyState />}
. For complex conditions, extract logic to variables or functions before the return statement. React automatically handles null, undefined, and false values by not rendering them.
Best Practice Note:
This is the same approach we use in CoreUI React components for loading states, error boundaries, and permission-based rendering.
Avoid using falsy numbers with &&
operator - use explicit boolean conversion: {items.length > 0 && <ItemList />}
instead of {items.length && <ItemList />}
to prevent rendering “0”.