Whilst working with React I find myself regularly mapping over an array of objects to render JSX elements. This week I had to solve a problem where I needed to have imported components inside objects and then to render each component respectively from the array of objects.
React knows it's a component
Luckily I found out that if you have an object with a key:value pair where value is a component then React understands it. This helps us when reading the object and rendering the component without extra effort.
import ComponentOne from './ComponentOne';
import ComponentTwo from './ComponentTwo';
const MyComponent = () => {
const arrOfObjects = [
{
id: 1,
name: 'car',
icon: <ComponentOne />,
},
{
id: 2,
name: 'bus',
icon: <ComponentTwo />
}
]
return (
<>
{arrOfObjects.map(obj => {
return (
<div key={obj.id}>
<h3>{obj.name}</h3>
{obj.icon}
</div>
)
})}
</>
)
}
Pass props to components inside objects
We can also pass props to a component in an object.
import ComponentOne from './ComponentOne';
import ComponentTwo from './ComponentTwo';
const MyComponent = () => {
const iconColor = '#eb4034';
const arrOfObjects = [
{
id: 1,
name: 'car',
icon: <ComponentOne stroke={iconColor} />,
},
{
id: 2,
name: 'bus',
icon: <ComponentTwo stroke={iconColor} />
}
]
And this is how we add components to an array of objects.