• 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!
Gal Normal

Another way to achieve conditional rendering in React is by using the ternary operator.

Geek Curious

How does the ternary operator work?

Gal Happy

The ternary operator is a shorthand for an if-else statement. It's written as condition ? expressionIfTrue : expressionIfFalse .

  • Using Ternary Operator for Conditional Rendering
Gal Pleased

Here's an example to help you understand how to use the ternary operator for conditional rendering in React!

function DisplayGreeting({ isLoggedIn }) {
    return (
        <div>
            {isLoggedIn ? (
                <h1>Welcome back, user!</h1>
            ) : (
                <h1>Please log in.</h1>
            )}
        </div>
    );
}
Geek Happy

I get it! If "isLoggedIn" is true, it displays "Welcome back, user!", otherwise, it shows "Please log in."

Gal Happy

Exactly! The ternary operator is a powerful and concise way to handle conditional rendering in React.

  • Hilarious Example
Geek Curious

Can you give me a funny example using the ternary operator?

Gal Pleased

Sure! Let's create a component that displays a fun fact if you're ready for it!

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>
    );
}
Geek Happy

Haha, that's amazing! If "isReady" is true, it shows the fun fact about snails, otherwise, it asks to be notified when ready for a fun fact.

Gal Happy

You got it! The ternary operator makes conditional rendering simple and fun. Enjoy experimenting with it!

  • 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! 😄