How to Conditional Render in React: Simple Patterns Explained
In React, you can conditionally render UI by using JavaScript expressions inside JSX with
if statements, the && operator, or the ternary operator condition ? true : false. These let you show or hide components based on state or props dynamically.Syntax
Conditional rendering in React uses JavaScript logic inside JSX to decide what to show. Common patterns include:
- If statement: Use outside JSX to choose what to return.
- Logical AND (
&&): Render something only if a condition is true. - Ternary operator (
condition ? true : false): Choose between two elements based on a condition.
jsx
function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back!</h1>; } return <h1>Please sign up.</h1>; } function Mailbox({ unreadMessages }) { return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2>You have {unreadMessages.length} unread messages.</h2>} </div> ); } function UserStatus({ isOnline }) { return ( <div> {isOnline ? <p>User is online</p> : <p>User is offline</p>} </div> ); }
Example
This example shows a simple React component that conditionally renders a greeting message based on whether the user is logged in or not. It uses an if statement to decide what to display.
jsx
import React, { useState } from 'react'; function Greeting() { const [isLoggedIn, setIsLoggedIn] = useState(false); return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>} <button onClick={() => setIsLoggedIn(!isLoggedIn)}> {isLoggedIn ? 'Log out' : 'Log in'} </button> </div> ); } export default Greeting;
Output
When loaded, the page shows "Please sign up." and a "Log in" button. Clicking the button toggles the message to "Welcome back!" and the button text changes to "Log out."
Common Pitfalls
Common mistakes when conditionally rendering in React include:
- Trying to use
ifstatements directly inside JSX, which is invalid syntax. - Returning
nullorfalseto hide elements instead of rendering empty fragments or nothing. - Forgetting to handle the
falsecase in ternary operators, leading to unexpected UI.
jsx
function WrongExample({ show }) { // This will cause a syntax error because if cannot be used inside JSX directly return ( <div> {/* {if (show) { <p>Show this</p> }} */} </div> ); } function RightExample({ show }) { return ( <div> {show ? <p>Show this</p> : null} </div> ); }
Quick Reference
Here is a quick summary of conditional rendering patterns in React:
Key Takeaways
Use JavaScript expressions like if, &&, and ternary operators to conditionally render in React.
Do not put if statements directly inside JSX; use them before the return or use ternary/&& inside JSX.
Ternary operators let you choose between two UI elements inline.
Logical AND (&&) renders an element only when the condition is true.
Always handle both true and false cases to avoid unexpected UI.