Table of Contents

How to render a List of React Elements (Component,…)?

About

This page is about Loop in React and Jsx.

Example

Basic Javascript vs React Loop

Example with Pure Javascript

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);
console.log(doubled);

where:

Example in React

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li>{number}</li>
);
ReactDOM.render(
  <ul>{listItems}</ul>,
  document.getElementById('root')
);
<div id="root"></div>

Advanced React with Key

By adding a key to the element, React can do a quicker reconciliation between two renderings to render only what have changed.

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>
        {number}
    </li>
  );
  return (
    <ul>{listItems}</ul>
  );
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);
<div id="root"></div>

Advanced with Loop in Jsx

Because JSX allows embedding any expressions in curly braces, we could inline the map() result of the previous example.

function NumberList(props) {
  const numbers = props.numbers;
  return (
    <ul>
      {numbers.map( (number) => (
        <li key={number.toString()}>{number}</li>
      ))}
    </ul>
  );
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);
<div id="root"></div>

Why a key

A key is a special string attribute you need to include when creating lists of elements (component,…) to allow a quick reconciliation (diff) between different renderings. They help React identify which items have been changed, added, or removed.

A key value is a string that uniquely identifies a list item among its siblings.

Rules:

If you need the same value in your component, pass it explicitly as a prop with a different name.

const content = posts.map((post) =>
  <Post
    key={post.id}
    id={post.id}
    title={post.title} />
);

You may read an in-depth explanation about why keys are necessary here.

1)