• Introduction In this section, we’ll dive into the If-Else in JSX for conditional rendering in React. We’ll explore how to use if-else statements inside JSX to create dynamic UIs. Let’s learn from Geek and Gal’s conversation!
Gal Normal

You know, sometimes you might want to use if-else statements in JSX for conditional rendering.

Geek Curious

Oh, interesting. How does that work?

Gal Happy

Well, you can't directly use if-else statements within JSX. However, there's a simple workaround using Immediately Invoked Function Expressions (IIFE).

  • Using If-Else in JSX with IIFE
Gal Pleased

Let me show you an example of how to use IIFE with if-else statements in JSX!

function DisplayMessage({ isLoggedIn }) {
    return (
        <div>
            {(() => {
                if (isLoggedIn) {
                    return <h1>Welcome back, user!</h1>;
                } else {
                    return <h1>Please log in.</h1>;
                }
            })()}
        </div>
    );
}
Geek Happy

I see! You've wrapped the if-else statement inside an IIFE, which is then called within the JSX.

Gal Happy

That's correct! Using IIFE with if-else statements allows you to conditionally render content within JSX.

  • Hilarious Example
Geek Curious

How about a funny example with if-else in JSX?

Gal Pleased

Sure! Let's create a component that displays a knock-knock joke if you're ready for it!

function KnockKnockJoke({ isReady }) {
    return (
        <div>
            {(() => {
                if (isReady) {
                    return (
                        <>
                            <p>Knock knock.</p>
                            <p>Who's there?</p>
                            <p>Alpaca who?</p>
                            <p>Alpaca the suitcase, you load up the car!</p>
                        </>
                    );
                } else {
                    return <p>Let me know when you're ready for a joke!</p>;
                }
            })()}
        </div>
    );
}
Geek Happy

Haha, that's hilarious! If "isReady" is true, it will display the knock-knock joke, otherwise, it will display a message asking to be notified when ready for a joke.

Gal Happy

Exactly! IIFE with if-else statements is a powerful tool for conditional rendering in JSX. Have fun exploring this technique!

  • Conclusion Using If-Else in JSX with Immediately Invoked Function Expressions (IIFE) is an effective way to achieve conditional rendering in React. It allows you to create dynamic UIs that can adapt to different conditions. Keep learning and experimenting to enhance your React skills! 😄