In this tutorial, we will show you how to show a simple list item, a list of objects, Nesting Lists in React, and lastly in React js application using state.
How to Display List in React JS App
Here are some examples of displaying a list of item, array and objects using different methods:
Show List using map()
To render array of objects items using map
(), here is the example:
import React from 'react';
function App() {
const Fruits = [
{ name: 'Apple' },
{ name: 'Apricot' },
{ name: 'Honeyberry' },
{ name: 'Papaya' },
{ name: 'Jambul' },
{ name: 'Plum' },
{ name: 'Lemon' },
{ name: 'Pomelo' }
];
return (
<div>
{Fruits.map(data => (
<p>{data.name}</p>
))}
</div>
);
}
export default App;
Render a List in React with Key
To render the list items with key using.map()
method, here is an example:
import React from 'react';
function App() {
const Movies = [
{ id: 1, name: 'Reservoir Dogs' },
{ id: 2, name: 'Airplane' },
{ id: 3, name: 'Doctor Zhivago' },
{ id: 4, name: 'Memento' },
{ id: 5, name: 'Braveheart' },
{ id: 6, name: 'Beauty and the Beast' },
{ id: 7, name: 'Seven' },
{ id: 8, name: 'The Seven Samurai' }
];
return (
<ul>
{Movies.map(data => (
<li key={data.id}> {data.name}</li>
))}
</ul>
);
}
export default App;
React Nested Lists
To show items in a nested list; here is an example:
import React from 'react';
function App() {
const users = [
{
id: '01',
name: 'John Deo',
email: '[email protected]',
phone: '202-555-0163'
},
{
id: '02',
name: 'Brad Pitt',
email: '[email protected]',
phone: '202-555-0106'
},
];
const joinList = [users, users];
return (
<div>
<ul>
{joinList.map((nestedItem, i) => (
<ul key={i}>
<h3> List {i} </h3>
{nestedItem.map(data => (
<li key={data.id}>
<div>{data.id}</div>
<div>{data.name}</div>
<div>{data.email}</div>
<div>{data.phone}</div>
</li>
))}
</ul>
))}
</ul>
</div>
);
}
export default App;
Conclusion
That’s it, You have learned how to show a simple list item, a list of objects, Nesting Lists in React, and lastly, we will have a look at how to update the state of the React list.