How to use .map() method in ReactJS?

Duomly - Jul 31 '20 - - Dev Community

This article was originally published at https://www.blog.duomly.com/6-most-popular-front-end-interview-questions-and-answers-for-beginners-part-2/#how-to-use-map-method-in-react-js


In the previous step of the React.js interview questions, we talked about iteration methods where we have put some lights on the for-loop and forEach methods.

We can now focus on the most popular method that we use to render the same elements from the lists, the map method.

Even if the map method is not the fastest, it is very popular, and you can see that method in most projects.

If you’re performance-oriented, don’t worry, it still is faster than forEach.

And has one more exciting feature when we compare that method to forEach, map method returns array when forEach returns an undefined value.

I’d say the map method is straightforward to use as well. Anyway, many tutorials recommend using the “index” value as the unique key of your element.

To care about performance, we shouldn’t do it, and we should use randomly generated id instead of the index one. Otherwise, our virtual DOM will re-render.

To see how to create a few same elements from the list, you can look at the code example:

function Welcome(props) {
  const products = ['orange', 'apple', 'watermelon'];
  return products.map(product=><li>{product}</li>)
}
Enter fullscreen mode Exit fullscreen mode

Duomly - Programming Online Courses

Thank you for reading,
Radek from Duomly

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player