Rendering Objects With The Map Function You can extend this even further by mapping over an array of objects. Now, instead of only having the name of each of the items within the array, you have an object for each item that includes the name and the price. Below, you have the array of objects named items, a component named List that contains a variable that maps over the items array and produces a list element of each of the objects within the array. Then, you are returning the variable that contains the list of items within the App component and finally rendering that list. Consider below: ... As you can see above, the mapping function now lives within the component rather than outside, which means you have to define props.items.map(). This is more common practice: do some functionality within the component then return markup. You also want any data you are using to live within the main component. That way, all data is in one spot.
import React from 'react';
import ReactDOM from 'react-dom';
const App = props => {
const items = [
{ name: 'Bread', price: 2.35 },
{ name: 'Milk', price: 2.0 },
{ name: 'Eggs', price: 3.15 },
{ name: 'Tea', price: 4.0 }
];
return <List items={items} />;
};
const List = props => {
const listItems = props.items.map((item, index) => (
<li key={index}>
{item.name}: {item.price}
</li>
));
return <ul>{listItems}</ul>;
};
ReactDOM.render(<App />, document.getElementById('root'));