How to render an array of objects in React?

user944513 picture user944513 · Dec 29, 2016 · Viewed 139.5k times · Source

could you please tell me how to render a list in react js. I do like this

https://plnkr.co/edit/X9Ov5roJtTSk9YhqYUdp?p=preview

class First extends React.Component {
  constructor (props){
    super(props);

  }

  render() {
     const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
    
    return (
      <div>
      hello
      </div>
    );
  }
} 

Answer

Shubham Khatri picture Shubham Khatri · Dec 29, 2016

You can do it in two ways:

First:

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);

    return (
      <div>
      {listItems }
      </div>
    );
  }

Second: Directly write the map function in the return

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    return (
      <div>
      {data.map(function(d, idx){
         return (<li key={idx}>{d.name}</li>)
       })}
      </div>
    );
  }