- Introduction In this section, we’ll explore the Ternary Operator for conditional rendering in React. The ternary operator is a concise and elegant way to handle conditional rendering. Let’s follow Geek and Gal’s conversation to learn more!
- Using Ternary Operator for Conditional Rendering
function DisplayGreeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<h1>Welcome back, user!</h1>
) : (
<h1>Please log in.</h1>
)}
</div>
);
}
- Hilarious Example
function FunFact({ isReady }) {
return (
<div>
{isReady ? (
<p>Did you know that a snail can sleep for up to 3 years? 😮</p>
) : (
<p>Let me know when you're ready for a fun fact!</p>
)}
</div>
);
}
- Conclusion The Ternary Operator is an effective way to achieve conditional rendering in React. It’s a concise alternative to if-else statements that helps you create dynamic UIs effortlessly. Keep learning and mastering new techniques to improve your React skills! 😄