Increase Your Efficiency Using Lists and Conditional Rendering

Loop Through Your Content

In code, you’ll often find that different lists of data are structured in the same way. Great news! 🤩 There's no need to strain over copying and pasting: you can just loop through your content and generate React components from it.Ā Ā 

But what would that look like?

Use the map() Method

The JavaScript Ā map()Ā  method passes over each element of an array. It applies a function and returns a new array containing the results of this function applied to each element.Ā 

For example, for a function that doubles the value of an element, it would look like this:

const numbers = [1, 2, 3, 4]
const doubles = numbers.map(x => x * 2) // [2, 4, 6, 8]

In our case,Ā you can use it to transform a list of dataĀ into a list of components.Ā Ā 

Ā Let’s create a Ā ShoppingList.jsĀ  component for our plant shop.

In this file, declare a Ā plantListĀ  variable, which containsĀ a list of plants:Ā 

const plantList = [
    'Monstera',
    'Ficus Lyrata',
    'Silver Pothos',
    'Yucca',
    'Palm'
]

Below that, add the component itself:Ā 

function ShoppingList() {
    return (
        <ul>
            {plantList.map((plant) => (
                <li>{plant}</li>
            ))}
        </ul>
    )
}

export default ShoppingList

As you can see, for each entry in the array, it returns a Ā <li>Ā  element.Ā 

Now import ShoppingList.js into Ā <App />Ā  Ā and… fantastic! We have our list of components. 🄳

But what’s this big red error on my console?

Console message that reads, Warning: Each child in a list should have a unique
Warning message on console.

Uh oh! Looks like the Ā keyĀ  Ā prop is missing. šŸ™ˆ

Define Your Key

Right, so what is theĀ Ā keyĀ  prop, and why do we need to worry about it here?

Ā React's documentation clearly explains this:Ā keyĀ props help ReactĀ identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array toĀ provide a stable identity.Ā Ā 

So I can give my key prop any value I like?Ā Ā 

Not quite! To avoid bugs, a key must follow these two rules:

  1. It should be unique within the array.

  2. It should be stable over time (the same source data should always have the same key= value).

Remember the virtual DOM in Part 1? The Ā keyĀ  is used toĀ link a piece of data to the corresponding component in the virtual DOM,Ā allowing for components to be generated. Ā 

Ā There are various methods for generating unique Ā keyĀ props:

  • The easiest and most reliable method is using the ID from data in your database.

  • You could also find a way to use the data valueĀ if you’re sure it will always be unique and stable over time.

  • As a last resort, you could define a string and combine it with the item index.Ā 

Since we don’t have an ID, we’ll combine the index and the plant name, which is a string:

function ShoppingList() {
    return (
        <ul>
            {plantList.map((plant, index) => (
                <li key={`${plant}-${index}`}>{plant}</li>
            ))}
        </ul>
    )
}

export default ShoppingList

AndĀ it's error free!

Give It a Go!

On branch P2C3-Begin-1, you’ll find the codebase you need to start the exercise. In Ā ShoppingList.jsĀ ,Ā  you’ll see a list of plants imported from Ā /datasĀ , called Ā plantListĀ ,Ā  and which consists of categories for each plant.Ā Ā 

Try the following, using this list of plants:

  • Dynamically put together a new list that extracts the unique plant categories (which we’ll use later on).

    • There are various ways of creating a list of unique items but use theĀ reduce()Ā  orĀ forEach()Ā method.

  • Display the list of plant categories above the list of plants for sale.Ā Ā 

The solution is on branch P2C3-Solution-1.Ā 

Contextualize Component Content

React allows you to create lists of components, saving developers vast amounts of time. But that’s not all! You can also use the JSX to render elements in components conditionally.Ā 

Remember that React allows you to evaluate a JavaScript expression in the JSX directly? That you can use curly braces to write a conditional to display one element or another?

Let'sĀ take this concept further, changing certain parts of our component depending on the context.

Create Conditions in JSX

You've already encountered the conditional operator. Now that we have a complete app to play around with, let's put it to work in our plant shop. šŸ¤“Ā 

In our list of plants Ā plantList.jsĀ  , add an isBestSaleĀ  category that corresponds to a Ā booleanĀ , which tells you whetherĀ a plant isĀ a best seller. It looks like this:Ā 

{
    name: 'Monstera',
    category: 'Classic',
    id: '1ed',
    isBestSale: true
},

Ā Now that we have our boolean,Ā let'sĀ use a conditional to display different emojis according to whether it is a best seller or not. In Ā ShoppingList.jsĀ  , on the same level as the name, add:

{plantList.map((plant) => (
    <li key={plant.id}>
        {plant.isBestSale ? <span>šŸ”„</span> : <span>šŸ‘Ž</span>}
    </li>
))}

Which gives us:

A bullet list of types of plant. Monstera and basil are followed by the flame emoji, while the others are followed by the thumbs down emoji.
A boolean allows us to distinguish bestsellers from non-bestsellers.

Great! It works!

On second thought, it might not work as a sales argument. šŸ¤”Ā  Instead, let’s just put šŸ”„Ā  for the best sellers and nothing for the others.

Ā To do that,Ā return Ā nullĀ  in the condition where you don’t want anything to be displayed:

{plant.isBestSale ? <span>šŸ”„</span> : null}

It works! 🤩
Do you know what, though? There’s an even easier way to write this – you can use Ā &&Ā  .Ā 

Ā Placed between curly braces,&&Ā goes before a JSX element and states that the element will only be generated if the condition is met. SoĀ you could write:

{plant.isBestSale && <span>šŸ”„</span>}

Which gives us:

The bullet list of types of plant with monstera and basil followed by a flame emoji while the others have no emoji.
Using an emoji to indicate only the bestsellers.Ā 

Yay! It works!

Try Alternative Methods

React is very flexible, and there are other methods you can use to add context to your content. I’ll run through a few of these in the screencast below:

Give It a Go!

You’ll find the codebase on branch P2C3-Begin-2. There's some CSS in Ā ShoppingList.cssĀ  so that everything’s a bit clearer. ✨ 

There's also aĀ Ā isSpecialOfferĀ  variable to Ā trueĀ  for plants on sale. Your mission is toĀ render a Ā divĀ  element that contains the word "Sale"Ā depending on whether the plant is on offer. You can pass it the Ā jh-salesĀ  class to add style.Ā 

Feel free to choose any of the methods from this chapter to create your conditional rendering.

You’ll find the solution on branch P2C3-Solution-2.

Let’s Recap!

  • Using a list of data, the Ā map()Ā  method creates a list of React components.

  • The Ā keyĀ  prop is essential in lists of components.Ā 

  • To avoid bugs, your Ā keyĀ  prop should:Ā 

    • Be unique within the list.

    • Remain the same over time.

  • Best practice for creating a Ā keyĀ  is using the data’s unique Ā idĀ  , and not using the item’s index.Ā 

  • Conditional rendering is used to render one element or another in the JSX, according to the condition ā€˜if… else...’.

  • There are other ways of creating conditions in React, such as taking the conditions out of the JSX.Ā 

In this chapter, you’ve mastered two extremely useful ways of saving time in React with conditions and lists. Congratulations!Ā 

In the next chapter,Ā we willĀ look at an essential element for reusing components in React: props! Can’t wait to get PROPerly acquainted? Then see you in the next chapter!Ā 

Ever considered an OpenClassrooms diploma?
  • Up to 100% of your training program funded
  • Flexible start date
  • Career-focused projects
  • Individual mentoring
Find the training program and funding option that suits you best