Celebrating 10 years in web hosting [email protected]

In this article, we can try to define ReactJS: how to use Lists and Keys, react Lists and Keys, and how can we use Lists and Keys in react.

Basic List Component

Usually, we would render lists inside a component. We can refactor the example of the previous article into a component that accepts an array of numbers and outputs a list of elements.

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

In this case, when you run this code, you’ll be given a warning that a key should be provided for list items.

Also, a “key” is a special string attribute we need to include when creating lists of elements.

You can purchase your hosting from Cloudsurph.comCloudsurph hosting is a reliable hosting option for business and personal projects. We offer insight and help on system configuration issues and code errors or bugs.

So, let’s assign a key to our list of items inside numbers.map() and fix the missing key issue like the below example.

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

Keys

Here, Keys help React identity which items have changed, are removed, or are added. Also, Keys should be given to the elements inside the array to give the elements a stable identity like the below example:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);

The best way the pick a key is to use a string that uniquely identifies a list item among its siblings and most often you would use IDs from your data as keys like the below example:

const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
);

Now, when you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort like the below example:

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

You can visit for the explanation about why keys are necessary if you’re interested in learning more.

You can check our article: AdonisJS: REST API simple CRUD Operation. IF you want then buy a good, reliable, secure web hosting service  from here: click here

Extracting Components with Keys

The Keys only make sense in the context of the surrounding array.

For like, if you extract a ListItem component, you should keep the key on the <ListItem /> elements in the array rather than on the <li> element in the ListItem itself.

Incorrect Key Usage example below:

function ListItem(props) {
  const value = props.value;
  return (
    // Wrong! There is no need to specify the key here:
    <li key={value.toString()}>
      {value}
    </li>
  );
}
function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // Wrong! The key should have been specified here:
    <ListItem value={number} />
  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

Correct Key Usage example below:

function ListItem(props) {
  // Correct! There is no need to specify the key here:
  return <li>{props.value}</li>;
}
function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // Correct! Key should be specified inside the array.
    <ListItem key={number.toString()} value={number} />
  );
  return (
    <ul>
      {listItems}
   </ul>
  );
}

Keys Must Only Be Unique Among Siblings

Here the Keys used within arrays should be unique among their siblings.

However, they don’t need to be globally unique and we can use the same keys when we produce two different arrays like the below example:

function Blog(props) {
  const sidebar = (
    <ul>
      {props.posts.map((post) =>
        <li key={post.id}>
          {post.title}
        </li>
      )}
    </ul>
  );
  const content = props.posts.map((post) =>
    <div key={post.id}>
      <h3>{post.title}</h3>
      <p>{post.content}</p>
    </div>
  );
  return (
    <div>
      {sidebar}
      <hr />
      {content}
    </div>
  );
}
const posts = [
  {id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
  {id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Blog posts={posts} />);

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

As in the below example:

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

Embedding map() in JSX

function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <ListItem key={number.toString()} value={number} /> ); return ( <ul> {listItems} </ul> ); }
JSX allows embedding any expression 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>
);
}

If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.