Skip to content
react

How to render array of components in React

Apr 7, 2023Abhishek EH3 Min Read
How to render array of components in React

You might often encounter scenarios to render a list of components. In this article, we will see how to do the same.

Project setup

Create a react app using the following command:

1npx create-react-app react-components-array

Now install the react-icons package:

1npm install react-icons

This is required since we will be displaying a list of icons.

Creating an array of components

Consider the following component:

1const Item = ({ value }) => {
2 return <li>{value}</li>
3}

We can create a list of items as shown below:

1const items = [<Item key={1} value={1} />, <Item key={2} value={2} />]

Rendering the component array

Rendering an array of components is as easy as rendering variables in React:

1import React from "react"
2
3const Item = ({ value }) => {
4 return <li>{value}</li>
5}
6
7const App = () => {
8 const items = [<Item key={1} value={1} />, <Item key={2} value={2} />]
9
10 return <ul>{items}</ul>
11}
12
13export default App

All you need to do is add the array within the flower brackets {items}.

You can dynamically create the array of components as shown below:

1import React from "react"
2
3const Item = ({ value }) => {
4 return <li>{value}</li>
5}
6
7const App = () => {
8 const items = Array.from({ length: 10 }).map((_, index) => (
9 <Item key={index} value={index + 1} />
10 ))
11
12 return <ul>{items}</ul>
13}
14
15export default App

Storing components in an Array of objects and rendering them

Consider the following array:

1import {
2 MdOutlinePhone,
3 MdOutlineFavorite,
4 MdOutlineContactPhone,
5} from "react-icons/md"
6
7const menu = [
8 {
9 name: "Recents",
10 icon: MdOutlinePhone,
11 },
12 {
13 name: "Favorites",
14 icon: MdOutlineFavorite,
15 },
16 {
17 name: "Contacts",
18 icon: MdOutlineContactPhone,
19 },
20]

If you want to render the icons stored inside the array, you can do so by using the following code:

1return menu.map(item => {
2 return (
3 <li key={item.name}>
4 <item.icon /> {item.name}
5 </li>
6 )
7})

The complete code would be:

1import React from "react"
2import {
3 MdOutlinePhone,
4 MdOutlineFavorite,
5 MdOutlineContactPhone,
6} from "react-icons/md"
7
8const menu = [
9 {
10 name: "Recents",
11 icon: MdOutlinePhone,
12 },
13 {
14 name: "Favorites",
15 icon: MdOutlineFavorite,
16 },
17 {
18 name: "Contacts",
19 icon: MdOutlineContactPhone,
20 },
21]
22
23const App = () => {
24 return menu.map(item => {
25 return (
26 <li key={item.name}>
27 <item.icon /> {item.name}
28 </li>
29 )
30 })
31}
32
33export default App

If you run the app now, you will see the following output:

list of icons

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com