Computer scienceFrontendReactList rendering

Introduction to rendering components

9 minutes read

One of the most common tasks for a frontend developer is displaying large data sets such as arrays and objects on the page. This data often comes from the backend, but it could also be local. The good news is, if you're familiar with JavaScript's map and filter methods, it'll be easy for you to learn how to turn arrays into visual elements in React. Let's review these methods and see how they can help manage data in React.

Intro to rendering

Before diving into map and filter methods, it's useful to understand what rendering actually is. Simply put, it's the process of displaying UI in the browser. In class-based components, we even have a render() function that tells React what to display on the screen. Let's briefly look at a class component:

import React from 'react';

class HelloWorld extends React.Component {
  render() {
    return (
      <h1>Hello, World!</h1>
    );
  }
}

export default HelloWorld;

In this example, the component displays the string "Hello, World" on the page. In functional components, you don't explicitly have a render() method. Instead, you return the JSX directly from the function. Since functional components are the modern syntax recommended by the React team, we'll stick to this method of creating components throughout this tutorial.

Let's build a simple App component that will display some information about you: your name, city, and favorite place in your city. Here's an example:

import React from 'react';

function App() {
   const person = { name: 'Nayana', city: 'Egypt', place: 'Saqqara' };

   return (
      <div>
         <h1>Hello, I'm {person.name}</h1>
         <p>I'm from {person.city}, my favorite place is {person.place}</p>
      </div>
   );
}

export default App;

The person is an object with three properties. To access them inside JSX, you'll need to use curly braces as demonstrated with {person.name}, {person.city}, and {person.place}. These curly braces let you embed dynamic values into your code. So, if you change some properties of the object in the future, React will catch this change and render the correct data.

The output:

dynamic values

If you got your results right, well done! Now let's see how to render bigger sets of data, such as arrays.

Now, let's look at how to render larger data sets, such as arrays.

Map method

The map method is a native JavaScript function used to loop through an array and transform every element in that array. In React, we can use this method to convert an array of data into an array of JSX elements.

Suppose we're building a cartoons' app. We receive an array of cartoons from the backend and want to display them on the page. Every cartoon is an object with three properties: name, year, and description. Here's how we can display the data on the page:

import React from 'react';

function App() {
   const cartoons = [
      {
         name: 'Scooby Doo',
         year: 1969,
         description:
            'Four best friends and their talking dog, Scooby-Doo, go on a series of adventures to solve puzzling and bizarre crimes.',
      },
      {
         name: 'Mickey Mouse',
         year: 1928,
         description:
            'Mickey Mouse, the most popular character of Walt Disney\'s animated cartoons and arguably the most popular cartoon star in the world.',
      },
      {
         name: 'Tom and Jerry',
         year: 1940,
         description:
            'The series features comic fights between an iconic set of adversaries, a house cat (Tom) and a mouse (Jerry)',
      },
   ];

   return (
      <div>
         {cartoons.map((cartoon, index) => (
            <div key={index}>
               <h2>{cartoon.name}</h2>
               <p>{cartoon.year}</p>
               <p>{cartoon.description}</p>
            </div>
         ))}
      </div>
   );
}

export default App;

We begin by opening a curly brace, because we want to insert JavaScript logic inside HTML. Then, we cycle through the cartoons array and for each item, we create a parent div with three child elements: a h2 for the name, a paragraph for the year, and another paragraph for the description. Finally, we close the curly brace. You can also see a key prop, which we'll talk more about later.

The output:

map example

Now, you might be wondering why we didn't use the forEach method. Technically, we could have, but it's not recommended. The key difference between forEach and map is that while forEach executes a provided function once for each element in the array, map creates a new array by calling a provided function on each element of the original array and returning the result. Since our goal is to create a new array of JSX elements, map is a better choice.

Let's say that we want to build an online store. We receive an array of products and want to list them on the page. Let's create a list of items and save it to the products variable:

const products = [
      { id: 1, brand: 'Iryna socks', img: 'https://shorturl.at/bepI9', price: 9.99 },
      { id: 2, brand: 'Rocky', img: 'https://shorturl.at/knqty', price: 12.99 },
      { id: 3, brand: 'Indiana', img: 'https://shorturl.at/hILOX', price: 10.79 },
      { id: 4, brand: 'Bella Inc', img: 'https://shorturl.at/kmuMU', price: 9.99 },
];

I encourage you to try rendering this list on your own, and then we'll walk through the solution together.

Just like in the previous example, we need to use the map method. We can create a wrapper div for each element in the list. That div will encapsulate all the information about each item: there can be an h3 tag for the brand name, an img tag to show the picture, and a div for the price info. Here's one way to do it:

import React from 'react';

function App() {
   const products = [
      { id: 1, brand: 'Iryna socks', img: 'https://shorturl.at/bepI9', price: 9.99 },
      { id: 2, brand: 'Rocky', img: 'https://shorturl.at/knqty', price: 12.99 },
      { id: 3, brand: 'Indiana', img: 'https://shorturl.at/hILOX', price: 10.79 },
      { id: 4, brand: 'Bella Inc', img: 'https://shorturl.at/kmuMU', price: 9.99 },
   ];

   return (
      <div style={{ textAlign: 'center' }}>
         <h1>Socks shop</h1>
         {products.map((product) => (
            <div key={product.id}>
               <h3>{product.brand}</h3>
               <img
                  src={product.img}
                  style={{ width: '150px', height: '150px', borderRadius: '10px' }}
               />
               <div>Get it for ${product.price} </div>
            </div>
         ))}
      </div>
   );
}

export default App;

I added some basic styles just to make the app look a bit better, but it's not mandatory; you can keep it simple. And here's the result:

online shop

There are two possible syntaxes for rendering JSX inside the map function. You can either directly return JSX (=> <div>{item}</div>), or open a function body and return JSX inside it like this: => {return <div>{item}</div>}.

What is key?

A key prop is a unique id that React uses to keep track of elements and correctly update or delete them when needed.

When rendering a list of elements using the map method in React, it's essential to assign a unique identifier to each element. React uses these identifiers to track and update only specific elements that have changed, instead of re-rendering the entire list. Without unique identifiers, React may have trouble figuring out which elements have changed, which can lead to potential bugs.

In our example above, we used an index of each element as a key prop. It's fine for educational purposes, but in general, using indexes isn't recommended. Instead, we could have used the name property, since every cartoon has a unique name.

You could also use special npm packages, such as uuid, which will generate unique keys for you automatically.

If you forget to include the key prop for some reason, the list will still render, but React will warn you in the console with the following error:

Warning: Each child in a list should have a unique "key" prop.

Filter method

The filter method is also a part of JavaScript that we can make use of in React. Like map, it creates a new array, but this new array will only contain the elements that pass a certain condition.

Let's go back to our cartoons' app. Now we only want to display cartoons that were released after 1950. This is where the filter method comes into play. First, below the cartoons array create a new constant called filtered. Loop through the cartoons array using the filter method and include only those cartoons that pass our test:

const filtered = cartoons.filter((cartoon) => cartoon.year > 1950);

Finally, just map through this array and show the same JSX elements:

import React from 'react';

function App() {
   const cartoons = [
      {
         name: 'Scooby Doo',
         year: 1969,
         description:
            'Four best friends and their talking dog, Scooby-Doo, go on a series of adventures to solve puzzling and bizarre crimes.',
      },
      {
         name: 'Mickey Mouse',
         year: 1928,
         description:
            'Mickey Mouse, the most popular character of Walt Disney’s animated cartoons and arguably the most popular cartoon star in the world.',
      },
      {
         name: 'Tom and Jerry',
         year: 1940,
         description:
            'The series features comic fights between an iconic set of adversaries, a house cat (Tom) and a mouse (Jerry)',
      },
   ];

   // add filtering method
   const filtered = cartoons.filter((cartoon) => cartoon.year > 1950);

   return (
      <div>
         {filtered.map((cartoon, index) => (
            <div key={index}>
               <h2>{cartoon.name}</h2>
               <p>{cartoon.year}</p>
               <p>{cartoon.description}</p>
            </div>
         ))}
      </div>
   );
}

export default App;

Great! Now our list only contains one cartoon:

filter example

In our socks app, we can filter the products by price. This kind of filtering mechanism is very common in online store development. Our user buys only expensive socks, so they want to see the products which prices are greater than 12. Let's sort this out.

import React from 'react';

function App() {
   const products = [
      { id: 1, brand: 'Iryna socks', img: 'https://shorturl.at/bepI9', price: 9.99 },
      { id: 2, brand: 'Rocky', img: 'https://shorturl.at/knqty', price: 12.99 },
      { id: 3, brand: 'Indiana', img: 'https://shorturl.at/hILOX', price: 10.79 },
      { id: 4, brand: 'Bella Inc', img: 'https://shorturl.at/kmuMU', price: 9.99 },
   ];
   const filtered = products.filter(product => product.price > 12)

   return (
      <div style={{ textAlign: 'center' }}>
         <h1>Socks shop</h1>
         {filtered.map((product) => (
            <div key={product.id}>
               <h3>{product.brand}</h3>
               <img
                  src={product.img}
                  style={{ width: '150px', height: '150px', borderRadius: '10px' }}
               />
               <div>Get it for ${product.price} </div>
            </div>
         ))}
      </div>
   );
}

export default App;

As we can see, the rendering logic is the same with one little difference is that now we are mapping through the filtered array that we defined above. Our products list contains only one item that satisfies our test, so in the output we should see Rocky brand:

filtered by price

Conclusion

Rendering, which refers to displaying UI in the browser, is a crucial aspect of React development. You use it to make your data visible to users by turning our data structures into visual elements on the screen. The map and filter methods are key tools that developers employ to render components in frontend applications. The map method transforms an array of data into an array of JSX elements. The filter method allows you to render elements conditionally, based on certain criteria. It's vital to specify the key prop during rendering, as it assists React in optimizing the process. Understanding these principles will enable you to effectively render and manage lists in your React applications.

10 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo