How to Use Inline Conditional Expressions in React
In React, inline conditional expressions allow you to render different UI elements or components based on certain conditions without needing a separate function or block of logic. This keeps your JSX clean and concise.
Here are the most common ways to use inline conditionals:
1. Using the Ternary Operator (condition ? true : false
)
The ternary operator is the most popular method for inline conditionals.
function Greeting({ isLoggedIn }) { return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} </div> ); }
- If
isLoggedIn
istrue
, it renders "Welcome back!". - If
false
, it renders "Please sign in."
2. Using Logical AND (&&
) Operator
If you only want to render something when a condition is true
, you can use &&
.
function Notification({ hasMessage }) { return ( <div> {hasMessage && <p>You have new messages!</p>} </div> ); }
- If
hasMessage
istrue
, it shows the paragraph. - If
false
, it renders nothing.
3. Using Logical OR (||
) Operator
You can use ||
when you want to render a fallback if a condition is false
.
function DefaultUser({ username }) { return ( <div> <h2>{username || "Guest"}</h2> </div> ); }
- If
username
is a truthy value, it shows the username. - If
username
is falsy (e.g.,null
,undefined
,""
), it displays "Guest".
Best Practices:
- Keep it simple: If the logic becomes too complex, consider extracting it into a separate function or variable.
- Be cautious with falsy values: When using
&&
, remember that values like0
,""
, andnull
are falsy and could cause unexpected behavior.
In short:
Inline conditional expressions in React let you dynamically render elements based on conditions, making your components more flexible and readable.