1. If-Else Statements in JSX Syntax
In React, JSX is an extension of JavaScript that allows you to write HTML-like code inside JavaScript files. It’s a core concept in React that helps render components dynamically. One common requirement in JSX is to conditionally render elements based on some logic. While JSX doesn’t support the typical(if-else) statements as we use in regular JavaScript, there are several ways to achieve conditional rendering.
1. Using Ternary Operator
The ternary operator is one of the most popular ways to include(if-else) logic directly in JSX. It’s compact and allows you to handle two conditions: a(true) or a (false).
function Welcome(props) {
return (
{props.isLoggedIn ? Welcome back!
: Please sign in
}
);
}
In this example, if props.isLoggedIn
is true
, the component renders "Welcome back!", otherwise, it renders "Please sign in."
2. Using Logical AND (&&) Operator
For situations where you only want to render something if a condition is true, the logical AND (&&) operator is handy.
function Notification(props) {
return (
{props.hasMessage && You have new messages
}
);
}
Here, the message will only display if (props.hasMessage) is (true). If it’s (false), nothing will be rendered.
3. Inline if-else with IIFE (Immediately Invoked Function Expression)
If you need more complex(if-else) logic that can’t be easily handled by a ternary operator, you can use an Immediately Invoked Function Expression (IIFE) in JSX.
function Greeting(props) {
return (
{(() => {
if (props.isLoggedIn) {
return Welcome back!
;
} else {
return Please sign in
;
}
})()}
);
}
This approach uses a JavaScript function inside JSX to handle the conditional rendering, giving you the flexibility of a typical (if-else) block.
4. Using if-else Outside of JSX
Another clean way to implement conditional logic is by writing the if-else
statements outside the JSX return block. This keeps the JSX tidy and readable
function Greeting(props) {
let message;
if (props.isLoggedIn) {
message = Welcome back!
;
} else {
message = Please sign in
;
}
return {message};
}