React - List of element (Component,...)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

Loop in React.

A “key” is a special string attribute you need to include when creating lists of elements (component,…)

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

Index example:

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

Using indexes for keys is not a good idea if the items can be reordered (it would be slow). You may read an in-depth explanation about why keys are necessary here.

A good rule of thumb is that elements inside the map() call need keys.

Keys Must Only Be Unique Among Siblings

Keys used within arrays should be unique among their siblings. However they don't need to be globally unique.

Keys serve as a hint to React but they don't get passed to your components. 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} />
);

JSX allows embedding any expressions in curly braces so we could inline the map() result:

function NumberList(props) {
  const numbers = props.numbers;
  return (
    <ul>
      {numbers.map((number) =>
        <ListItem key={number.toString()}
                  value={number} />
      )}
    </ul>
  );
}
Advertising

3 - Example

3.1 - 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>

3.2 - Advanced

  • NumberList is a component that accepts an array of numbers and outputs an unordered list of elements.
index.jsx
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')
);
index.html
<div id="root"></div>

Advertising

4 - Documentation / Reference