How to Use Conditional Rendering in JSX in React
In React, you use
conditional rendering in JSX by embedding JavaScript expressions like if statements, ternary operators, or logical && inside curly braces. This lets you show or hide parts of the UI based on conditions dynamically.Syntax
Conditional rendering in JSX uses JavaScript expressions inside curly braces {}. You can use:
- If statements: Usually outside JSX to decide what to render.
- Ternary operator: Inline condition with
condition ? true : false. - Logical AND operator: Render something only if a condition is true with
condition && element.
jsx
function Greeting({ isLoggedIn }) { return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>} </div> ); }
Example
This example shows how to use the ternary operator and logical AND for conditional rendering. It displays a welcome message if the user is logged in, or a sign-up prompt if not.
jsx
import React, { useState } from 'react'; function App() { const [isLoggedIn, setIsLoggedIn] = useState(false); return ( <div> {isLoggedIn ? ( <h1>Welcome back!</h1> ) : ( <h1>Please sign up.</h1> )} {isLoggedIn && <p>You have new notifications.</p>} <button onClick={() => setIsLoggedIn(!isLoggedIn)}> {isLoggedIn ? 'Logout' : 'Login'} </button> </div> ); } export default App;
Output
When isLoggedIn is false: Shows 'Please sign up.' and a 'Login' button.
When isLoggedIn is true: Shows 'Welcome back!', 'You have new notifications.', and a 'Logout' button.
Common Pitfalls
Common mistakes include:
- Trying to use
ifstatements directly inside JSX, which is not allowed. - Returning
falseornullunintentionally, which can cause nothing to render. - Using the logical AND operator when the left side can be a value that renders unexpectedly (like 0).
jsx
function WrongExample({ count }) { return ( <div> {/* This will cause an error because if is not an expression */} {/* if (count > 0) { return <p>Count is positive</p>; } */} {/* Correct way using ternary */} {count > 0 ? <p>Count is positive</p> : <p>Count is zero or negative</p>} {/* Logical AND pitfall: if count is 0, it renders 0 */} {count && <p>Count is {count}</p>} {/* Safer way: explicitly check */} {count > 0 && <p>Count is {count}</p>} </div> ); }
Quick Reference
Here is a quick summary of conditional rendering patterns in JSX:
Key Takeaways
Use JavaScript expressions inside curly braces {} for conditional rendering in JSX.
Prefer the ternary operator for simple if-else conditions inside JSX.
Use logical AND (&&) to render elements only when a condition is true.
Avoid using if statements directly inside JSX; place them outside or use expressions.
Watch out for values like 0 with && as they can render unexpectedly.