DEV Community

Cover image for React basics: Looping a list
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

React basics: Looping a list

In today's article for React basics, we'll enhance our first ever React components with a list.

Yesterday we made some static book components like so:

<Book title='Laravel collections' />
<Book title='Ruby for beginners' />
<Book title='CSS is awesome' />
Enter fullscreen mode Exit fullscreen mode

However, that quickly becomes a struggle to maintain. So let's have a look at how we could dynamically load these books from a list.

Creating a list in React

Open up your App.js and add a list like so above your app declaration.

const books = [
  {
    id: 1,
    title: 'Laravel collections',
  },
  {
    id: 2,
    title: 'Ruby for beginners',
  },
  {
    id: 3,
    title: 'CSS is awesome',
  },
];

function App() {}
Enter fullscreen mode Exit fullscreen mode

To render these elements in our React app, we can leverage the map function.

<Bookshelf>
    {books.map((book) => (
      <Book title={book.title} />
    ))}
</Bookshelf>
Enter fullscreen mode Exit fullscreen mode

And this little piece of code will do the same thing as we had before.

Keys in React

However, I made one big mistake in the example above.
When we render list items in React as we do above, we should always set a key property.
This key will help React identify which items change or should be removed.

To add the key, we can use the following code.

<Book title={book.title} key={book.id} />
Enter fullscreen mode Exit fullscreen mode

However, sometimes we just do not have a key, so what do we do then?

Well, no worries, React comes with a built-in index we can use as the key.

const numbers = [1, 2, 3];

{numbers.map((number, index) => (
    <span key={index}>Number: {number}</span>
))}
Enter fullscreen mode Exit fullscreen mode

As you can see, the index is available on the map function to use that as the unique key for each element.

As usual, you can find this code on GitHub.
I hope you enjoyed this article about loops in React.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (3)

Collapse
 
bemmio profile image
Edward Mike

Great 👍

Collapse
 
dailydevtips1 profile image
Chris Bongers

Glad you like it Edward

Collapse
 
waylonwalker profile image
Waylon Walker

Making over objects to make elements is suck a key part to any framework.