JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Encountered two children with the same key error in React

Author:JIYIK Last Updated:2025/03/17 Views:

When two or more elements we map()return from the method have the same key property, we get the React error “ Encountered two children with the same key ”. To fix the error, you need to provide a unique value for the key prop of each element or use the index parameter.

Look at the following code

const App = () => {
  // 👇️ name property is not a unique identifier
  const people = [
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
    {id: 3, name: 'Alice'},
  ];

  /**
   * ⛔️ Encountered two children with the same key, `Alice`.
   *  Keys should be unique so that components maintain their identity across updates.
   *  Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
   */
  return (
    <div>
      {people.map(person => {
        return (
          <div key={person.name}>
            <h2>{person.id}</h2>
            <h2>{person.name}</h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;

Encountered two children with the same key error in React

The problem in the code snippet is that we are using name as the key attribute on each object, but the name attribute is not unique across all objects.

One way to work around the error is to use the index, which is map()the second argument passed to the function taken by the method.

const App = () => {
  const people = [
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
    {id: 3, name: 'Alice'},
  ];

  // 👇️ now using index for key
  return (
    <div>
      {people.map((person, index) => {
        return (
          <div key={index}>
            <h2>{person.id}</h2>
            <h2>{person.name}</h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;

The function we pass to Array.mapthe method is called with each element in the array and the index of the current element being processed.

The index is guaranteed to be unique, but using it for the key attribute is not a best practice because it is unstable and can change between renders.

A better solution is to use a value to uniquely identify each element in the array.

In our example, we can use the id property on the object, since each id is guaranteed to be unique.

const App = () => {
  const people = [
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
    {id: 3, name: 'Alice'},
  ];

  // ✅ now using the id for the key prop
  return (
    <div>
      {people.map(person => {
        return (
          <div key={person.id}>
            <h2>{person.id}</h2>
            <h2>{person.name}</h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;

Using id as the key attribute is much better because we guarantee that the object with id 1 will always have a name attribute equal to Alice.

For performance reasons, React uses keythe value we pass to the property — to ensure that it only updates list elements that changed between renders.

When each element in an array has a unique key, React can more easily determine which list elements have changed.

We could use keyan index on the property, but this would likely cause React to do more work behind the scenes instead of using a stable value like a unique id.

Having said that, unless you are presenting arrays with thousands of elements, there is a good chance that you will not notice any difference between using an index and a unique identifier.

Summarize

When two or more elements we map()return from the method have the same key property, we get the React error "Encountered two children with the same key". To resolve the error, provide a unique value for the key prop of each element or use the index parameter.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:166 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial