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:
npx create-react-app react-components-array
Now install the react-icons package:
npm install react-icons
This is required since we will be displaying a list of icons.
Creating an array of components
Consider the following component:
const Item = ({ value }) => {
return <li>{value}</li>
}
We can create a list of items as shown below:
const 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:
import React from "react"
const Item = ({ value }) => {
return <li>{value}</li>
}
const App = () => {
const items = [<Item key={1} value={1} />, <Item key={2} value={2} />]
return <ul>{items}</ul>
}
export 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:
import React from "react"
const Item = ({ value }) => {
return <li>{value}</li>
}
const App = () => {
const items = Array.from({ length: 10 }).map((_, index) => (
<Item key={index} value={index + 1} />
))
return <ul>{items}</ul>
}
export default App
Storing components in an Array of objects and rendering them
Consider the following array:
import {
MdOutlinePhone,
MdOutlineFavorite,
MdOutlineContactPhone,
} from "react-icons/md"
const menu = [
{
name: "Recents",
icon: MdOutlinePhone,
},
{
name: "Favorites",
icon: MdOutlineFavorite,
},
{
name: "Contacts",
icon: MdOutlineContactPhone,
},
]
If you want to render the icons stored inside the array, you can do so by using the following code:
return menu.map(item => {
return (
<li key={item.name}>
<item.icon /> {item.name}
</li>
)
})
The complete code would be:
import React from "react"
import {
MdOutlinePhone,
MdOutlineFavorite,
MdOutlineContactPhone,
} from "react-icons/md"
const menu = [
{
name: "Recents",
icon: MdOutlinePhone,
},
{
name: "Favorites",
icon: MdOutlineFavorite,
},
{
name: "Contacts",
icon: MdOutlineContactPhone,
},
]
const App = () => {
return menu.map(item => {
return (
<li key={item.name}>
<item.icon /> {item.name}
</li>
)
})
}
export default App
If you run the app now, you will see the following output:
Top comments (0)