Learn React · 5/13

Rendering Lists & Conditional Rendering

6 min read

Rendering Lists & Conditional Rendering 📜

Welcome, React adventurer! So, you've learned how to render single elements. But what if you have a whole collection of items? A list of users, a gallery of images, or a series of notifications? And what if you only want to show some of those things some of the time? Fear not, for this guide will equip you with the essential tools of rendering lists and showing content when you want to.


1. Rendering Arrays of Data using .map() 🗺️

The Problem: Imagine you have an array of your favorite travel destinations, and you want to display each one on your webpage. You could write out the HTML for each destination one by one, but what if that list changes? What if you add a new dream destination? You'd have to go back and manually update your code. That's not very dynamic, is it? It's like having to reprint an entire book just to fix a single typo.

The Solution: The .map() Method

In JavaScript, arrays have a wonderfully useful method called .map(). It allows you to create a new array by calling a function for every element in the original array. In React, we can use this to transform an array of data into an array of JSX elements.

Let's see it in action. Suppose we have an array of travel spots:

javascript
const destinations = ['Tokyo', 'Paris', 'New York', 'Bora Bora'];

We can use .map() to create a list of these destinations:

jsx
import React from 'react';

function DestinationList() {
  const destinations = ['Tokyo', 'Paris', 'New York', 'Bora Bora'];

  return (
    <div>
      <h2>My Dream Destinations</h2>
      <ul>
        {destinations.map(destination => (
          <li>{destination}</li>
        ))}
      </ul>
    </div>
  );
}

export default DestinationList;

What's happening here?

  1. We have our destinations array.
  2. Inside our component's return statement, we use {} to embed a JavaScript expression.
  3. We call destinations.map(). For each destination in the destinations array, it returns a <li> element containing the destination's name.
  4. React then takes this array of <li> elements and renders them into the DOM.

It's like having a magical blueprint (<li>{destination}</li>) and a list of materials (destinations array). The .map() function is the machine that takes each material and builds a product according to the blueprint, resulting in a complete set of items.

✨ Fun Fact: The .map() method is a core concept of functional programming. By using it, you're not changing the original destinations array; you're creating a new one. This immutability is a key principle in React for predictable state management.


2. The Importance of "Keys" in React Lists 🔑

The Problem: In our previous example, everything seems to work fine. However, if you open your browser's developer console, you might see a warning from React: Warning: Each child in a list should have a unique "key" prop. What's that all about?

Imagine you have a list of identical twins, and you want to give one of them a cookie. If you don't have a way to tell them apart, you might give the cookie to the wrong twin, or give one twin two cookies and the other none! React faces a similar problem. When you update a list (add, remove, or reorder items), React needs a way to identify which items have changed.

The Solution: The key Prop

The key is a special string attribute you need to include when creating lists of elements. Keys give the elements a stable identity.

Let's update our DestinationList component to include keys. A good key should be something that uniquely identifies an item among its siblings. Often, your data will have a unique id property, which is perfect for a key. If you don't have stable IDs for rendered items, you may use the item's index as a key as a last resort.

jsx
import React from 'react';

function DestinationList() {
  const destinations = [
    { id: 1, name: 'Tokyo' },
    { id: 2, name: 'Paris' },
    { id: 3, name: 'New York' },
    { id: 4, name: 'Bora Bora' }
  ];

  return (
    <div>
      <h2>My Dream Destinations</h2>
      <ul>
        {destinations.map(destination => (
          <li key={destination.id}>{destination.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default DestinationList;

Why is this so important?

Without keys, React might have to re-render the entire list every time it changes. With keys, React can be much more efficient. It can tell if an item was added, removed, or just moved, and only make the necessary changes in the DOM. Think of it as a super-efficient inventory management system for your UI elements.

Industry Practice: Using an item's index from the .map() function (e.g., (destination, index) => <li key={index}>) is generally discouraged if the list can be reordered, as this can lead to bugs and performance issues. Always try to use a unique identifier from your data.


3. Conditional Rendering with Ternary Operators (? :) 🤔

The Problem: Your app's UI is rarely static. You often need to show or hide elements based on certain conditions. For example, you might want to show a "Log In" button for guests and a "Log Out" button for logged-in users.

The Solution: The Ternary Operator

The ternary operator is a concise way to write an if-else statement in a single line. It's perfect for simple conditional rendering in JSX.

The syntax is: condition ? expressionIfTrue : expressionIfFalse

Let's create a component that displays a different message depending on whether a user is logged in.

jsx
import React from 'react';

function Greeting({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome back!</h1>
      ) : (
        <h1>Please sign up.</h1>
      )}
    </div>
  );
}

export default Greeting;

In this example, if isLoggedIn is true, the component will render "Welcome back!". If it's false, it will render "Please sign up.". It's like a bouncer at a club checking your ID; depending on whether you have one, you either get in or you're told to go home.


4. Short-circuit Evaluation (&&) in UI 💡

The Problem: Sometimes you only want to render something if a condition is true, and do nothing otherwise. You could use a ternary operator and return null for the false case, but there's an even cleaner way.

The Solution: The Logical && Operator

In JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false. React takes advantage of this. If the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

Let's say we want to show the number of unread messages, but only if there are any.

jsx
import React from 'react';

function Mailbox({ unreadMessages }) {
  return (
    <div>
      <h2>Hello!</h2>
      {unreadMessages.length > 0 && (
        <h3>
          You have {unreadMessages.length} unread messages.
        </h3>
      )}
    </div>
  );
}

export default Mailbox;

Here, the <h3> element will only be rendered if unreadMessages.length is greater than 0. It's like a secret agent who only reveals themselves if their mission is active. If not, they remain hidden.

This is a very common and elegant pattern in React for conditionally including an element.


📚 Further Reading & Resources

Challenge

Challenge Instructions

Your task is to create a React functional component named UserActivityFeed.

This component will receive a single prop: activities. The activities prop is an array of objects, where each object represents a user action and has the following structure:
{ id: string, user: string, type: 'comment' | 'like', isNew: boolean }

Your component must adhere to the following requirements:

  1. Render an unordered list (<ul>) containing the activities.
  2. Iterate over the activities array to create a list item (<li>) for each activity object.
  3. Assign a unique and stable key to each <li> element using the id from the activity object.
  4. Inside each <li>, display the user's name followed by a description of their action. Use a ternary operator to determine the description: if the type is 'comment', display ' posted a comment'; otherwise, display ' liked a post'.
  5. If the isNew property is true, you must also render a <strong> tag with the text ' (New!)' right after the action description. This tag should not be rendered if isNew is false. Use logical AND (&&) for this conditional rendering.

Expected result

Your code should implement the UserActivityFeed component. The solution must use the .map() method on the activities prop to generate the list items.

  • Each <li> must have a key prop assigned with activity.id.
  • A ternary operator (? :) must be used to conditionally display either ' posted a comment' or ' liked a post' based on activity.type.
  • A short-circuit && operator must be used to conditionally render the <strong> (New!)</strong> element only when activity.isNew is true.

Given the sampleActivities data, the rendered component should produce an HTML structure equivalent to the following:

html
<ul>
  <li key="a1s2d">John Doe posted a comment<strong> (New!)</strong></li>
  <li key="f3g4h">Jane Smith liked a post</li>
  <li key="j5k6l">Sam Wilson liked a post<strong> (New!)</strong></li>
  <li key="q7w8e">Chris Lee posted a comment</li>
</ul>
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.