# Lists

Official Docs. (opens new window)

Lets say we have a list of users that we want to show in a list:

const users = [
	{ id: '01', name: 'leni' },
	{ id: '02', name: 'alex' },
];

In React, transforming arrays into lists of elements is nearly as we do it in JavaScript.

You can build collections of elements and include them in JSX using curly braces {}.

Lets loop through the users array using the JavaScript map (opens new window) function and return a list item element for each user and store the resulting array.

const users = [
	{ id: '01', name: 'leni' },
	{ id: '02', name: 'alex' },
];
const usersList = users.map((user) => <li>{user.name}</li>);

Now we can include the intire usersList array inside a list element and render it to the DOM:

ReactDOM.render(<ul>{usersList}</ul>, document.getElementById('root'));

Usually you would render lists inside a component.

Lets create a component that accepts an array of users and output their names.

const UsersList({ users }) = () => {
  const usersList = users.map((user) => <li key={user.id}>{user.name}</li>);

  return <ul>{usersList}</ul>
}

const users = [
	{ id: '01', name: 'leni' },
	{ id: '02', name: 'alex' },
];

ReactDOM.render(<UsersList users={users} />, document.getElementById('root'));

# Keys

WARNING

A "key" is a special string attribute you need to include when creating lists of elements.

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys.

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const usersList = users.map((user, index) => <li key={index}>{user.name}</li>);