How to Conditionally Render Components in React
In React, conditional rendering means displaying different UI elements or components based on certain conditions, just like how we use conditions (if-else) in JavaScript.
Here are the most common ways to conditionally render components:
1. Using if-else Statements
You can use regular JavaScript if-else
statements before the return
statement to decide what to render.
function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back!</h1>; } else { return <h1>Please sign up.</h1>; } }
2. Using Ternary Operator
For simple conditions, you can use a ternary operator inside JSX.
function Greeting({ isLoggedIn }) { return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>} </div> ); }
3. Using Logical AND (&&
) Operator
If you want to render something only when a condition is true
, you can use the &&
operator.
function Dashboard({ hasNotifications }) { return ( <div> <h1>Dashboard</h1> {hasNotifications && <p>You have new notifications!</p>} </div> ); }
- If
hasNotifications
istrue
, the message will appear. - If
hasNotifications
isfalse
, nothing will render.
4. Using Switch-Case (for Multiple Conditions)
When there are multiple conditions, using a switch
statement can make your code cleaner.
function Status({ status }) { switch (status) { case 'loading': return <p>Loading...</p>; case 'success': return <p>Data loaded successfully!</p>; case 'error': return <p>Error loading data.</p>; default: return null; } }
5. Immediately Invoked Function Expressions (IIFE)
Sometimes for complex conditions, you can wrap logic inside an immediately invoked function inside JSX.
function UserProfile({ user }) { return ( <div> {(() => { if (!user) return <p>Loading...</p>; if (user.isAdmin) return <h1>Admin: {user.name}</h1>; return <h1>User: {user.name}</h1>; })()} </div> ); }
Summary
- Use if-else for clearer separation of logic.
- Use ternary inside JSX for simple true/false conditions.
- Use logical AND (
&&
) when you want to render something based on a single true condition. - Use switch-case for multiple distinct cases.
- Use IIFE for more complex or inline conditional logic.
Conditional rendering is a powerful tool that helps you build dynamic and user-friendly React applications!