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> ); } }
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.
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.
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.
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!
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> ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With