Using If-Else and Ternary Operators in JSX
0 991
🔀 Using If-Else and Ternary Operators in JSX
Conditional rendering is one of the most powerful techniques in React. It lets you decide what to show based on state, props, or other conditions. In JSX, you can’t use traditionalif-else directly inside the return — but React gives us multiple ways to work around that! 💡
📠Why We Need Conditional Rendering
Sometimes you want to: 🔓 Show login/logout buttons based on authentication📦 Show loading spinners while data is loading
âš ï¸ Display errors when something goes wrong Let’s explore how to use if-else, ternary, logical &&, and function-based conditionals inside JSX.
⌠Traditional If-Else Doesn’t Work in JSX
// ⌠Invalid inside JSX return
return (
if (loggedIn) {
Welcome!
} else {
Please log in.
}
);
This throws a syntax error — because JSX is just syntactic sugar for JavaScript function calls.
✅ 1. Using Ternary Operator (? :)
The most common and clean way to conditionally render in JSX is using a ternary expression:const isLoggedIn = true;
return (
{isLoggedIn ?
Welcome back! :
Please log in.}
);
📌 Use this when you have two options to toggle between.
✅ 2. Logical AND (&&) for Single Conditions
If you only want to show something conditionally and show nothing otherwise, use&&:
const hasMessages = true;
return (
{hasMessages &&
📩 You have new messages!}
);
📌 This is cleaner than ternary if you don’t need an “else†case.
✅ 3. Storing Logic Outside JSX
You can write a fullif-else block outside the return statement:
let content;
if (isLoading) {
content =
Loading...;
} else if (error) {
content =
Something went wrong!;
} else {
content =
Data loaded successfully.;
}
return {content};
📌 This is great for complex logic — keeps JSX clean and readable.
✅ 4. Using Functions for Complex Logic
You can create a helper function for large conditional blocks:const renderUserStatus = () => {
if (loading) return
Loading user...;
if (!user) return
User not found.;
return
👤 Welcome, {user.name};
};
return {renderUserStatus()};
📌 Ideal when rendering varies based on multiple conditions or nested logic.
âš ï¸ Avoid Overusing Nested Ternaries
// 😵 Confusing to read
{isLoggedIn ? (isAdmin ?
Admin Panel :
User Dashboard) :
Please log in}
Tip: Split it into a helper function or use if blocks outside JSX for better readability.
🧠Recap
ⓠJSX doesn’t allow raw if-else inside return✅ Use ternary
? : for two-choice conditions✅ Use logical AND
&& when there’s no else condition✅ Use variables/functions outside JSX for complex logic Clean conditional rendering makes your UI more dynamic and responsive without turning your JSX into spaghetti code! ðŸ
🚀 What’s Next?
🔠Learn conditional class rendering withclassnames🌗 Explore state-based toggling (like themes or tabs)
ðŸ—ï¸ Build custom UI components like loaders or alerts based on state Now that you understand conditionals in JSX, your React apps can adapt to anything users throw at them! 🔥
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants.
Start your journey today!
Share:




Comments
Waiting for your comments