Rendering Lists in React
Published: 2024-02-15 07:38:07

## Introduction
Rendering lists is a common task in modern web applications, especially when dealing with dynamic content such as movie listings, food orders, or book catalogs. As developers, it's crucial to master the art of manipulating and displaying lists effectively. In this tutorial, we'll explore how to render lists in React to enhance user experiences in the apps we build.

## Prerequisites
1. Fundamental knowledge of HTML, JavaScript, and React
2. A code editor to follow along

## Table of Contents
* Transforming Lists with the `map()` method
* Rendering Lists in components
* Using Keys Within Lists
* Conclusion

***

In the real world, a list is a simple collection of elements, often represented as an array in JavaScript. Lists become essential when fetching data from external sources, such as APIs. For example, when creating a book listing app, you'll need to retrieve a list of books from an API and transform the data before displaying it to users. This is where the map() method becomes invaluable.

## Transforming Lists with the `map()` method

The map() method allows us to selectively display data to users by iterating through an array, applying a callback function to each element, and constructing a new array from the results.

Let's consider how to transform a list of book items using the map() method in JavaScript. When working with lists in JavaScript, you'll use the array type specific to your data. In this tutorial, we'll transform data obtained from a third party (using an array of JavaScript objects) with the map() method.

The [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method is used for iterating through an array, calling a provided callback function for each element, and constructing a new array from the results.

Here's a snippet of the data:

```json
export const bookList = [
{
  id: 0,
  title: "Atomic Habits",
  author: "James Clear",
  frontCover: "https://m.media-amazon.com/images/I/513Y5o- DYtL.jpg",
  backCover: "https://m.media- amazon.com/images/I/81DCnP7ntKL._AC_UF1000,1000_QL80_.jpg",
  datePublished: "2018",
  purchaseLink: "https://www.amazon.com/Atomic-Habits-James-Clear- audiobook/dp/B07RFSSYBH",
},

{
  id: 1,
  title: "Outliers",
  author: "Malcolm Gladwell",
  frontCover: "https://m.media-amazon.com/images/I/51CFbC0HoeL.jpg",
  backCover: "https://www.shopyaar.com/upload/product/a69375492ef2da69b89c3093a32e375e.jpg",
  datePublished: "2008",
  purchaseLink: "https://www.amazon.com/Outliers-Malcolm-Gladwell-audiobook/dp/B001LNK9C4/ref=sr_1_1?adgrpid=116047907195&hvadid=585359320515&hvdev=c&hvlocphy=21541&hvnetw=g&hvqmt=e&hvrand=8987847268972473835&hvtargid=kwd-298703248067&hydadcr=10787_13491799&keywords=outliers&qid=1699642346&s=books&sr=1-1",
},
{
  id: 2,
  title: "The 10X Rule",
  author: "Grant Cardone",
  frontCover: "https://m.media-amazon.com/images/I/51txCrB2JqL.jpg",
  backCover: "https://bookbins.in/wp-content/uploads/2021/05/The-10x-Rule-Grant-Cardone-Buy-Online-Bookbins-2.png",
  datePublished: "2011",
  purchaseLink: "https://www.amazon.com/dp/B005DGW34C?plink=Ic0UuVbawSdTNyjo&pf_rd_r=H132JYJ316N8X5G3YZY5&ref_=adblp13npsbx_1_3_im",
},
...
] 
```
Each book item in the list has properties such as `id`, `title`, `author`, `frontCover`, `backCover`, `datePublished`, and `purchaseLink`.

Now, let's create a new variable to hold the transformed data using the map() operation.

```javascript
const data = bookList.map(book => {
return book
})

console.log(data)
```

![transformed data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ivk4f5ylkjh6bi74116u.png)

The data logged to the console is the basic structure of a map transformation. With this new array returned, we can now access the book's properties.

## Rendering Lists in components
What we've done so far is transform the data received from the third party into the right form that can be rendered.

With React, we can further transform this list of books into a collection of React components. Utilizing the map() method in conjunction with the JSX syntax, we can create a BookList component.

```javascript
//bookList component

const BookList = () => {
const data = bookList.map(book => {
  return book
})

console.log(data)

return (
	<div>
	{data.map((book) => (
	<div>
		<img src={book.frontCover} />
		<h1>{book.title}</h1>
		<h2>{book.author}</h2>
		<div>
			<h4>{book.datePublished}</h4>
			<a
				href={book.purchaseLink}
				target="_blank"
			>
				Buy here
			</a>
		</div>
	</div>
	))}
	</div>
 );
};

export default BookList;

```
This will now be displayed on the webpage. Additional CSS has been added to ensure proper display of book items. You can find the complete code here.


![Rendered list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cy9jbsrw92hgknh8m76.png)

## Using Keys Within Lists
Keys are unique identifiers that help React identify which element has been modified, added, or removed from the DOM.
In React, using keys is crucial for dynamic list updates. These unique identifiers help React's Diffing algorithm efficiently manage changes within the component tree. 

React's diffing algorithm compares the current virtual DOM with the previous one, identifying added, removed, or modified elements. While generally effective, occasional inconsistencies may arise, emphasizing the importance of unique keys.

There are several ways to use keys in a component, including external libraries and the Math.random() function. Another approach is to use the item's index. This works well to an extent in preventing duplicates and preserving the internal state of the list item. However, if the order of items in your list may change, you should not use this approach because it can negatively impact the performance of your app and cause glitches. The best practice is to use predefined keys in your data. 

Let's modify the component to use keys. Our data already has an id property, so we can use it as our key.

```javascript
//bookList component

...

return (
	<div>
	{data.map((book) => (
	<div key={book.id}>
		{/*rest of JSX code*/}
	</div>
	))}
	</div>
 );
};

export default BookList;

```
Adding the key at the top-level element helps prevent optimization issues, especially in larger applications.

## Conclusion
In conclusion, rendering lists in React is a fundamental skill for building dynamic and user-friendly applications. The map() method, combined with proper key usage, helps you to efficiently display and manage lists. By mastering these techniques, you can enhance the user experience of your React applications.