Lists

Expand your knowledge on lists and learn how you can manage them effectively in React.

We'll cover the following

Rendering a list

Lists refer to plain JavaScript arrays. They’re a collection of simple data that can be iterated over. They are essential for React, even plain JavaScript development, and it is hard to imagine developing without them. ES2015+ offers many nice declarative methods such as Array.map(), Array.filter() or Array.find() that can even be used as expressions in JSX (if surrounded by curly brackets {}). Let’s recap expressions in JSX briefly: Arrays can be used as an expression in JavaScript and therefore also be included in JSX. If surrounded by curly brackets, they will be treated as child nodes during the transpilation step.

But there’s more. Array.map() enables us to not only work with data but it can also return modified items which in turn can also contain JSX. This adds further flexibility and allows us to transform data sets into React elements.

Let’s assume that we want to show a list of cryptocurrencies. The array containing the data has the following form:

const cryptos = [
  {
    id: 1,
    name: 'Bitcoin',
    symbol: 'BTC',
    quotes: { EUR: { price: 7179.92084586 } },
  },
  {
    id: 2,
    name: 'Ethereum',
    symbol: 'ETH',
    quotes: { EUR: { price: 595.218568203 } },
  },
  {
    id: 3,
    name: 'Litecoin',
    symbol: 'LTC',
    quotes: { EUR: { price: 117.690716234 } },
  },
];

First, we will aim to show this data as a simple unordered list in HTML. A resulting component could look similar to this:

const CryptoList = ({ currencies }) => (
  <ul>
    {currencies.map((currency) => (
      <li>
        <h1>
          {currency.name} ({currency.symbol})
        </h1>
        <p>{currency.quotes.EUR.price.toFixed(2)} €</p>
      </li>
    ))}
  </ul>
);

The component could then be used like this:

<CryptoList currencies={cryptos} />

Let’s see this in action.

Get hands-on with 1200+ tech skills courses.