Sometimes, we want to render an array of objects in React.
In this article, we’ll look at how to render an array of objects in React.
How to render an array of objects in React?
To render an array of objects in React, we can use the array map
method.
For instance, we write
const Item = (props) => {
return <li>{props.message}</li>;
};
const TodoList = () => {
const todos = ["foo", "bar", "baz"];
return (
<ul>
{todos.map((message) => (
<Item key={message} message={message} />
))}
</ul>
);
};
to call todos.map
with a callback toi render the Item
component with the message
value.
We set the key
prop to a unique value for each entry so that React can identify each item being rendered.
Conclusion
To render an array of objects in React, we can use the array map
method.