close
close

🚀 Day 5: Exploring List Rendering and Conditional Rendering in React🚀

🚀 Day 5: Exploring List Rendering and Conditional Rendering in React🚀

Welcome to day 5 of my React learning journey! Today, I delved into some fundamental React concepts that are essential for building dynamic and interactive applications: rendering of lists and various techniques for conditional rendering. These concepts are essential for managing how components are displayed based on data and user interactions. Here’s what I learned:

Render Lists

In React, rendering lists involves iterating over an array of data and creating components for each element in the array. This is typically done using JavaScript map method. Here is an example using a list of pizza items:

Below is the list of pizzas:

const pizzaData = (
    {
        name: "Focaccia",
        ingredients: "Bread with Italian olive oil and rosemary",
        price: 6,
        photoName: "https://imgur.com/C3Ca4BS.png",
        soldOut: false,
    },
    {
        name: "Pizza Margherita",
        ingredients: "Tomato and mozzarella",
        price: 10,
        photoName: "https://imgur.com/lipmW8F.png",
        soldOut: false,
    },
    {
        name: "Pizza Spinaci",
        ingredients: "Tomato, mozzarella, spinach, and ricotta cheese",
        price: 12,
        photoName: "https://imgur.com/APdaPZR.png",
        soldOut: false,
    },
    {
        name: "Pizza Funghi",
        ingredients: "Tomato, mozzarella, mushrooms, and onion",
        price: 12,
        photoName: "https://imgur.com/dPpvWzM.png",
        soldOut: false,
    },
    {
        name: "Pizza Salamino",
        ingredients: "Tomato, mozzarella, and pepperoni",
        price: 15,
        photoName: "https://imgur.com/9dtZJNE.png",
        soldOut: true,
    },
    {
        name: "Pizza Prosciutto",
        ingredients: "Tomato, mozzarella, ham, arugula, and burrata cheese",
        price: 18,
        photoName: "https://imgur.com/jii9M6S.png",
    },
);
Enter full screen mode

Exit full screen mode

The Pizza component is written as follows:

function Pizza({ pizzaObj }) {
    return (
        <li className="pizza">
            <img src={pizzaObj.photoName} alt={pizzaObj.name} />
            <div>
                <h3>{pizzaObj.name}</h3>
                <p>{pizzaObj.ingredients}</p>
                <span>{pizzaObj.price}</span>
            </div>
        </li>
    );
}
Enter full screen mode

Exit full screen mode

We can render the list using map array function like:

<ul className="pizzas">
    {pizzas.map((pizza) => (
        <Pizza pizzaObj={pizza} key={pizza.name} />
    ))}
</ul>
Enter full screen mode

Exit full screen mode

List rendering

Key points

  • Iteration: THE map The method is used to iterate over the pizzaData table, creation of a Pizza component for each pizza object.
  • Accessories: Each pizza object is passed to the Pizza component via accessories for rendering.
  • Unique keys: A unique key an accessory is provided to each Pizza component, which is essential to help React efficiently identify and manage components when rendering.

Conditional Rendering Techniques

Conditional rendering in React allows you to dynamically display elements based on certain conditions. Today, I explored several common conditional rendering techniques:

1. Conditional rendering with && Operator

THE && The operator is used for conditional rendering when you want to display an element only if a certain condition is true.

Example: Footer component

function Footer() {
    const hour = new Date().getHours();
    const openHour = 10;
    const closeHour = 22;
    const isOpen = hour >= openHour && hour <= closeHour;

    return (
        <footer className="footer">
            {isOpen && (
                <p>
                    We're happy to welcome you between {openHour}:00 and{" "}
                    {closeHour}:00.
                </p>
            )}
        </footer>
    );
}
Enter full screen mode

Exit full screen mode

This example uses the && operator to conditionally return a message if the current time is within operating hours.

Operator && rendered

Example: menu component

function Menu() {
    const pizzas = ();

    return (
        <>
            <h1>Our Menu</h1>

            {pizzas.length > 0 && (
                <ul className="pizzas">
                    {pizzas.map((pizza) => (
                        <Pizza pizzaObj={pizza} key={pizza.name} />
                    ))}
                </ul>
            )}
        </>
    );
}
Enter full screen mode

Exit full screen mode

In this example, the list of pizzas is rendered only if there are items in the pizzas painting.

List of pizzas with &&

2. Conditional rendering with ternary operator

The ternary operator is useful when you have two possible outcomes depending on a condition.

Example: menu component

function Menu() {
    const pizzas = ();

    return (
        <>
            <h1>Our Menu</h1>

            {pizzas.length > 0 ? (
                <ul className="pizzas">
                    {pizzas.map((pizza) => (
                        <Pizza pizzaObj={pizza} key={pizza.name} />
                    ))}
                </ul>
            ) : (
                <p>
                    We're still working on our menu. Please come back later :)
                </p>
            )}
        </>
    );
}
Enter full screen mode

Exit full screen mode

This example uses the ternary operator to decide whether to return the list of pizzas or a message that the menu is being prepared.

Ternary Conditional Rendering

Example: Footer component

function Footer() {
    const hour = new Date().getHours();
    const openHour = 10;
    const closeHour = 22;
    const isOpen = hour >= openHour && hour <= closeHour;
    console.log(isOpen);

    return (
        <footer className="footer">
            {isOpen ? (
                <p>
                    We're open from {openHour}:00 to {closeHour}:00. Come visit
                    us or order online.
                </p>
            ) : (
                <p>
                    We're happy to welcome you between {openHour}:00 and{" "}
                    {closeHour}:00.
                </p>
            )}
        </footer>
    );
}
Enter full screen mode

Exit full screen mode

In this example, the ternary operator is used to return different messages depending on whether the restaurant is open or not.

3. Conditional rendering with multiple returns

Using multiple return statements allows you to exit a component earlier than expected based on a condition.

Example: Footer component

function Footer() {
    const hour = new Date().getHours();
    const openHour = 13;
    const closeHour = 22;
    const isOpen = hour >= openHour && hour <= closeHour;
    console.log(isOpen);

    if (!isOpen) {
        return <h1>CLOSED</h1>;
    }

    return (
        <footer className="footer">
            <p>
                We're open from {openHour}:00 to {closeHour}:00. Come visit us
                or order online.
            </p>
        </footer>
    );
}
Enter full screen mode

Exit full screen mode

Here, if the restaurant is closed, the function returns earlier with a CLOSED message, otherwise it continues to display the opening hours message.

Example: Pizza Component

function Pizza({ pizzaObj }) {
    if (pizzaObj.soldOut) {
        return null;
    }

    return (
        <li className="pizza">
            <img src={pizzaObj.photoName} alt={pizzaObj.name} />
            <div>
                <h3>{pizzaObj.name}</h3>
                <p>{pizzaObj.ingredients}</p>
                <span>{pizzaObj.price}</span>
            </div>
        </li>
    );
}
Enter full screen mode

Exit full screen mode

In this example, if a pizza is sold out, the component returns nullwhich means nothing is returned for this pizza.

Key points to remember

  • Efficiency:Conditional rendering enables efficient rendering of components, ensuring that only necessary elements are displayed based on the current state or data.
  • Flexibility:Each technique offers different levels of flexibility and readability, making it easier to choose the method most appropriate for your specific use case.

Conclusion

Today’s learning path has equipped me with the skills to effectively handle list rendering and conditional rendering in React. These techniques are the backbone of building interactive, data-driven user interfaces. I look forward to applying these concepts as I continue my React learning journey.

Stay tuned for more updates as I dive deeper into React!

Check out my GitHub for code examples and projects.
Connect with me on LinkedIn to stay up to date with my latest projects and ideas!