How to loop array or array of objects in React?
Use JavaScript’s map() function to iterate over arrays and render dynamic lists in React.
Question
How to loop array or array of objects in React?
Answer
React doesn’t have its own loop mechanism — you use JavaScript’s map() to loop through data and render components dynamically.
Example for an array of strings:
function TodoList() {
const todos = ['Code', 'Eat', 'Sleep', 'Repeat'];
return (
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
);
}
For an array of objects:
const users = [
{ id: 1, name: 'Ghazi' },
{ id: 2, name: 'John' },
];
function Users() {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Real-World Example
Looping data from APIs to render cards, tables, or lists.
Quick Practice
Create a ProductList that displays products fetched from an array of objects.
Summary
Use map() to transform data into JSX elements. Always include a key for performance and correctness.
Why use map() instead of for loop?
Because map() returns a new array of JSX elements directly usable in rendering.
Why is key prop important?
It helps React identify and efficiently update list items.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.