Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering an array.map() in React

People also ask

How do you render a map in React?

In React, the map() function is most commonly used for rendering a list of data to the DOM. To use the map() function, attach it to an array you want to iterate over. The map() function expects a callback as the argument and executes it once for each element in the array.

How do you map an array data in React?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.

Can I render an array in React?

To render an array of components in React you simply need to pass the array into JSX by wrapping it in curly braces, just be sure that your components each have a unique key prop because React will use this when rendering it to avoid bugs.

How do you use a map map in React?

To use a map() inside a map() function in React: Call map() on the outer array, passing it a function. On each iteration, call the map() method on the other array.


Gosha Arinich is right, you should return your <li> element. But, nevertheless, you should get nasty red warning in the browser console in this case

Each child in an array or iterator should have a unique "key" prop.

so, you need to add "key" to your list:

this.state.data.map(function(item, i){
  console.log('test');
  return <li key={i}>Test</li>
})

or drop the console.log() and do a beautiful oneliner, using es6 arrow functions:

this.state.data.map((item,i) => <li key={i}>Test</li>)

IMPORTANT UPDATE:

The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id if id already there, or just generate unique ids for it.


You are not returning. Change to

this.state.data.map(function(item, i){
  console.log('test');
  return <li>Test</li>;
})

let durationBody = duration.map((item, i) => {
      return (
        <option key={i} value={item}>
          {item}
        </option>
      );
    });

You are implicitly returning undefined. You need to return the element.

this.state.data.map(function(item, i){
  console.log('test');
  return <li>Test</li>
})