Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render an array of objects in React?

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>     );   } }  
like image 400
user944513 Avatar asked Dec 29 '16 06:12

user944513


People also ask

How do I render multiple arrays of objects in React?

To render multiple JSX elements in React, you can loop through an array with the . map() method and return a single element. In the next example, you will examine why you would want to add a unique key to a list of elements rendered by an array.

How do you render an array of objects?

To render an array of objects in react with JSX we need to use Array. map() to transform the object into something react can make use of because you cannot directly render an object into React. Instead, by using Array.

How do you render an array of React elements?

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 render multiple objects React?

To render multiple elements in React, you can use the Array's map functionality. Simply map all your objects into React fragments, so that your Function component can make use of it. But don't forget to set a unique key prop!


1 Answers

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>     );   } 
like image 53
Shubham Khatri Avatar answered Oct 12 '22 23:10

Shubham Khatri