Published: September 13 2020

React - Display a list of items

Other versions available:

This is a quick example to show how to display a list of items in React.

The example simply renders an array of user objects as rows in a table using the array map function inside the JSX returned by the React component.

Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/react-display-list-of-items)


Example React component that renders the users array

The react app component declares the users state variable with the useState hook function and sets the initial state to a hardcoded array of users.

In the return JSX the component loops over the users with the array map function (users.map(user => ...)) and renders a table row for each user that includes the user name, email and role.

import React, { useState } from 'react';

function App() {
    const [users, setUsers] = useState([
        { id: 1, firstName: 'Frank', lastName: 'Murphy', email: '[email protected]', role: 'User' },
        { id: 2, firstName: 'Vic', lastName: 'Reynolds', email: '[email protected]', role: 'Admin' },
        { id: 3, firstName: 'Gina', lastName: 'Jabowski', email: '[email protected]', role: 'Admin' },
        { id: 4, firstName: 'Jessi', lastName: 'Glaser', email: '[email protected]', role: 'User' },
        { id: 5, firstName: 'Jay', lastName: 'Bilzerian', email: '[email protected]', role: 'User' }
    ]);

    return (
        <div className="container">
            <h3 className="p-3 text-center">React - Display a list of items</h3>
            <table className="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Role</th>
                    </tr>
                </thead>
                <tbody>
                    {users && users.map(user =>
                        <tr key={user.id}>
                            <td>{user.firstName} {user.lastName}</td>
                            <td>{user.email}</td>
                            <td>{user.role}</td>
                        </tr>
                    )}
                </tbody>
            </table>
        </div>
    );
}

export { App };


Render an array of objects with index instead of id

If you have an array of objects that don't have a unique property (e.g. id) that you can use for the key prop, it's possible to use the item index which is provided by the array map function.

This is how the above map function would look using the item index instead of the id as the key prop:

{users && users.map((user, index) =>
    <tr key={index}>
        ...
    </tr>
)}

 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by