Answered
In a React.js page, I have data being pulled into the page via an external REST API.
It's in the form of an array of objects that looks similar to this:
[
{
"id": 1,
"title": "Post title 1",
"description": "Description for post 1."
},
{
"id": 2,
"title": "Post title 2",
"description": "Description for post 2."
}, {
"id": 3,
"title": "Post title 3",
"description": "Description for post 3."
},
. . .
]
How can I render all of those items on the page? And make sure all are displayed regardless of how many objects are in the array?
The map()
function is what you're looking for.
Here's an example of how you'd render each object in the array you provided:
class YourComponent extends React.Component {
render() {
return (
<>
{
array.map((item, index) => {
return (
<div key={index}>
<h2>{item.title}</h2>
<p>{item.description}</p>
</div>
)
})
}
</>
)
}
}
This will display both the title and description for each item in the array.