In JavaScript, data often comes as an array of objects. In React, we use the map() method to transform each item in the array into JSX elements for rendering in the browser.
const list = [
{
title: 'React',
url: 'https://react.dev/',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0,
},
{
title: 'Redux',
url: 'https://redux.js.org/',
author: 'Dan Abramov, Andrew Clark',
num_comments: 2,
points: 5,
objectID: 1,
},
];function App() {
return (
{list.map(function (item) {
return - {item.title}
;
})}
);
}This renders each item’s title inside a <li> element.
React requires a key attribute for each list item to optimize rendering. Use a unique identifier like objectID:
{list.map(function (item) {
return {item.title} ;
})}If no unique ID is available, you can use the index as a last resort, though it’s not recommended for dynamic lists.
To display more information, such as the URL, author, comments, and points:
{list.map(function (item) {
return (
{item.title}
{item.author}
{item.num_comments}
{item.points}
);
})}{}.href can be dynamically assigned from data.{/* comment */} for comments inside JSX.Using map() to render lists in React is a powerful way to display dynamic data. With JSX, you can mix logic and markup seamlessly. The key attribute ensures efficient re-rendering, and JSX syntax allows you to express complex UI structures with clarity and flexibility.