List rendering is a crucial part of any web application. In this blog, we will explore the use of the map method and how to render lists in React.
What are Lists?
Lists are very useful to create or improve the UI of any website. They are mainly used for displaying menus on a website, for instance, the navbar menu. In regular JavaScript, we use arrays for creating lists. We can similarly create lists in React as we do in regular JavaScript.
In React, you can use the map()
method to iterate over an array and render each item in a list.
Map Method
Here's an example of a map function that takes an array of 5 numbers and multiplies their values by 5:
const numbers = [1, 2, 3, 4, 5];
const Multiply = numbers.map((num) => num * 5);
console.log(Multiply);
// Output: [ 5, 10, 15, 20 ,25 ]
The map()
method iterates over each element in the numbers
array and then the callback function is called which multiplies each number by 5 and returns the result in a new array.
Rendering a Simple List
Let's create a component and call it HeroList
. We'll create a list of hero names by iterating over an array of hero names, and render the heroList.
import React from 'react'
function HeroList() {
const heroes = ["Clark", "Thor", "T'Challa"]
const heroList = heroes.map(hero => <h2>{hero}</h2>)
return <div>{heroList}</div>
}
export default HeroList
You can see in the output that the list is successfully rendered to the browser.
Rendering an Array of Objects as a List
Let's say we want to define an array of hero objects with each object containing properties for id
, name
, superName
, and homeTown
.
const heroes = [
{
id: 1,
name: "Clark",
superName: "SuperMan",
homeTown: "Krypton"
},
{
id: 2,
name: "Thor",
superName: "God of Thunder",
homeTown: "Asgard"
},
{
id: 3,
name: "T'Challa",
superName: "Black Panther",
homeTown: "Wakanda"
}
]
Heroes Component
Let's also create a separate component and name it "Heroes Component". The component will take a single prop named "hero" and we will destructure it and return the hero information wrapped in an h2
tag.
import React from 'react'
function Heroes({hero}) {
return (
<div>
<h2>
I am {hero.name}, a.k.a {hero.superName}. I am from {hero.homeTown}
</h2>
</div>
)
}
export default Heroes
HeroList Component
We want to render a list of three hero cards, with each hero card displaying information about a hero.
In the HeroList
Component map method, we import the Heroes
Component and pass in the hero as a prop to the Heroes
Component.
For each hero in the heroes
array, a new Heroes
component is created with the hero
object passed as a prop. The array of resulting Heroes
components is then stored in the "heroList" array.
import React from 'react'
import Heroes from './Heroes'
function HeroList() {
const heroes = [
{
id: 1,
name: "Clark",
superName: "SuperMan",
homeTown: "Krypton"
},
{
id: 2,
name: "Thor",
superName: "God of Thunder",
homeTown: "Asgard"
},
{
id: 3,
name: "T'Challa",
superName: "Black Panther",
homeTown: "Wakanda"
}
]
const heroList = heroes.map(hero => <Heroes hero={hero} />)
return (
<div>
{heroList}
</div>
)
}
export default HeroList
The HeroList
component renders the resulting array of Heroes
components as a list.
Each Heroes
component is rendered in the heroList
array, with the appropriate hero information displayed for each one:
Pretty Good..!!
However, if you look at the console, you will find:
The warning is about using a unique key. So, what are Keys?
Keys
The key
attribute is essential when rendering lists in React. Keys allow React to keep track of elements. This way, if a list item is updated or removed, only that item will be re-rendered instead of the entire list. They let us uniquely identify an item between its siblings.
Note: Keys must be unique among siblings and must not change.
The key
should be a unique identifier, most preferably an ID. Although not recommended, we can also use the array index as a key.
In this case, we will pass the key
prop to the Heroes
component and use the hero.id
property as the key
value, like this:
const heroList = heroes.map(hero => <Heroes key={hero.id} hero={hero} />)
Let's check out the updated code in the HeroList
component:
import React from 'react'
import Heroes from './Heroes'
function HeroList() {
const heroes = [
{
id: 1,
name: "Clark",
superName: "SuperMan",
homeTown: "Krypton"
},
{
id: 2,
name: "Thor",
superName: "God of Thunder",
homeTown: "Asgard"
},
{
id: 3,
name: "T'Challa",
superName: "Black Panther",
homeTown: "Wakanda"
}
]
const heroList = heroes.map(hero => <Heroes key={hero.id} hero={hero} />)
return (
<div>
{heroList}
</div>
)
}
export default HeroList
This code will give the same output as the previous code but this time without any warning.
And that's it..!! ❤️❤️
To Summarize
List rendering is a common task in React, where a list of items are dynamically rendered based on some data. The map()
method is generally used to transform an array of data into an array of React elements.
When rendering a list in React, it's important to assign a unique key
prop to each item in the list. This helps React optimize the rendering process by minimizing the number of DOM updates required when the list changes.
Overall, list rendering is a fundamental skill for React developers that can be used in many different types of applications, from simple to complex.
Resources
Thank you for taking the time to read this blog. Hope you found it informative and enjoyable!
In the next article of this series, we shall take a look at React Events.
Catch you guys on the next one. Cheers .. ✌️