Simple example:
const strings = ['Flowers', 'Pots', 'Soil'];
const listItems = strings.map(string => <li>{string}</li>);
<ul>{listItems}</ul>
Another example:
export default function App() {
const elements = data.map(item => {
return <Card img={item.img} info={item.info} />
})
return (
<div>
{elements}
</div>
)
}
The map method can be used in a variety of ways. From rendering lists, components, to different elements.
function Card(props) {
const professors = [
{id: 1, subject: "math", name: "Roberts"},
{id: 2, subject: "english", name: "Tucker"},
{id: 2, subject: "math", name: "Smith"},
{id: 2, subject: "english", name: "Tucker"},
{id: 2, subject: "math", name: "Marks"},
{id: 2, subject: "math", name: "James"}
];
const mathTeachers = professors.filter(teacher => teacher.subject === 'math');
const list = mathTeachers.map(teacher =>
<div>
<h2> {teacher.name} </h2>
<p> {teacher.contactInfo} </p>
</div>
);
return (
<div>{list}</div>
)
};
Filter out certain items first then map them.
const list = jobs.map((job, i) =>
<li key={'job-' + i}>{job}</li>
);
Used to keep items in order.
export default function App() {
const cards = data.map(item => {
return (
<Card
key={item.id}
img={item.coverImg}
rating={item.stats.rating}
reviewCount={item.stats.reviewCount}
location={item.location}
title={item.title}
price={item.price}
/>
)
});
return (
<div>
{cards}
</div>
)
}
A good example of using map to map components.