📘 Understanding map()
in React - A Beginner's Guide
React is all about creating reusable components and rendering dynamic content. One of the most common tasks in React is to display a list of items. This is where JavaScript’s map()
function becomes super useful!
✅ What is map()
?
map()
is a built-in JavaScript function that lets you loop over an array and return a new array.
In React, we use map()
to render multiple elements from an array.
📝 Example 1: List of Names
Let’s say we have a list of names, and we want to display each one in a list:
function NameList() {
const names = ['Shubham', 'Anjali', 'Ravi'];
return (
<ul>
{names.map((name, index) => (
<li key={index}>{name}</li>
))}
</ul>
);
}
What’s happening?
- We have an array
names
. - We use
names.map()
to go through each name and return a <li> element. key
is a unique identifier React needs when rendering lists.
📝 Example 2: List of Students with Marks
What if each item is an object?
function StudentList() {
const students = [
{ name: 'Aman', marks: 80 },
{ name: 'Nina', marks: 92 },
{ name: 'Rahul', marks: 75 }
];
return (
<div>
{students.map((student, index) => (
<p key={index}>
{student.name} scored {student.marks} marks.
</p>
))}
</div>
);
}
This shows how map()
is useful for looping through an array of objects and rendering multiple JSX elements.
🚀 Summary
map()
is used to loop through arrays.- In React, it helps render a list of elements dynamically.
- Always provide a unique
key
when rendering lists.
Start using map()
to make your UI dynamic and data-driven!
💡 Try editing one of the examples above to show your own data. You’ll learn React faster by experimenting!
0 Comments