React keys - rendering 2 duplicate items in a list- how to avoid same key warning as same items are intended without using index as key?

Asked
Active3 hr before
Viewed126 times

9 Answers

usingreact
90%

Can I avoid informal personal interactions at companies that offer free lunch? , How is a crossword clue to be interpreted when it contains (… includes part of #-Direction)? ,How can I accomplish this without passing in index.

@sushant has essentially answered but here's the code

this.state.cards.map((card,index)=> {
  return <div key={index}><img src={card.src} /> <div/>
}
88%

When you are rendering React components in a map function inside the render function, you must provide a key prop to each component that is unique, otherwise React will put a warning in the console and may or may not correctly update your component when it rerenders. One of the most common mistakes is using an object as the key. An object will get stringifyed by React into [object Object] regardless of the specifics of the object you passed in. So two completely different objects will have the same key. If this happens you will see something like a warning like the following in the console:,Warning: Encountered two children with the same key, [object Object]. 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.,The best practice in situations like this is to use the unique ID backing your objects. In this example, the user’s ID that would have been stored in the database. However it’s possible to use other hashing functions to get similar results.

Warning: Encountered two children with the same key, [object Object]. 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.

render() {
    return (
        <div>
            {this.state.users.map(user => (
                <UserComponent user={user} key={user} />
            ))}
        </div>
    )
}
load more v
72%

In React, transforming arrays into lists of elements is nearly identical.,Let’s assign a key to our list items inside numbers.map() and fix the missing key issue.,We include the entire listItems array inside a <ul> element, and render it to the DOM:

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

When trying to render a list of elements without passing a key prop, you’ll be given a warning that a key should be provided for list items.,“We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.” — according to React’s docs.,In this article, I want to show you how to wisely use the key props when rendering lists, and also the problems you might face when passing index to it.

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Note how the "My Awesome Button" was not rendered above and React just rendered an empty HTML button element. React will not warn you in this case.,The bigger problem here is when you decide to name your component button or img. React will ignore your component and just render a vanilla HTML button or img tag.,If the component name does not start with a capital letter, the component use will be treated as a built-in element such as a div or span.

class greeting extends React.Component {
   // ...
}
load more v
40%

The solution is to just not use the same key. Your keys must be unique.,Creating React Components,The bug: Starting a React component's name with a lowercase letter.

function App() { // Error: Nothing was returned from render  return;}
load more v
22%

The <List> component fetches the list of records from the data provider, and renders the default list layout (title, buttons, filters, pagination). It delegates the rendering of the list of records to its child component. Usually, it’s a <Datagrid>, responsible for displaying a table with one row for each record.,The List view displays a list of records fetched from the API, and allows users to filter, sort, select, and paginate the records. You can display the list as a Datagrid, a list of images, a calendar, or using a component of your own.,By default, the <List> uses the <Pagination> component for pagination. This component displays buttons to navigate between pages, including buttons for the surrounding pages.

// in src/posts.js
import * as React from "react";
import { List, Datagrid, TextField, DateField, BooleanField } from 'react-admin';

export const PostList = (props) => (
    <List {...props}>
        <Datagrid>
            <TextField source="id" />
            <TextField source="title" />
            <DateField source="published_at" />
            <TextField source="category" />
            <BooleanField source="commentable" />
        </Datagrid>
    </List>
);

// in src/App.js
import * as React from "react";
import { Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';

import { PostList } from './posts';

const App = () => (
    <Admin dataProvider={jsonServerProvider('https://jsonplaceholder.typicode.com')}>
        <Resource name="posts" list={PostList} />
    </Admin>
);

export default App;
load more v
60%

Also the docs explicitly say “If you choose not to assign an explicit key to list items then React will default to using indexes as keys” which can therefore be considered stable behavior.,The semantics aren’t an implementation detail. The semantics are “If no key is specified, identity is defined by the order of the elements”, which is exactly the same as “…by the index into the array of elements”. Also the docs explicitly say “If you choose not to assign an explicit key to list items then React will default to using indexes as keys” which can therefore be considered stable behavior.,When you don’t provide an explicit key, React will internally use the index as key and emit a warning – however you would want to silence the warning, as using the index here is perfectly valid.

<div suppressKeyWarning>
   {/* No keys required here... */}
   {[<div>first</div>]}
    {/* But keys are required here, and the warning was suppressed! */}
    {this.state.items.map(item => <div>{item}</div>}
</div>
load more v
48%

React makes sure you know about this rule with keys—if you render a list of items without keys React throws a console error in development.,Index as a key is an anti-pattern: this article describes a couple potential bugs that can come from using index as the key prop.,We need to use a unique value for each key. This is important—duplicate keys in our array React will throw another console error!

const items = ['A', 'B', 'C']

const MyList = () => {
  return (
    <ul>
      {items.map(letter => (
        <li>{letter}</li>
      ))}
    </ul>
  )
}
load more v

Other "using-react" queries related to "React keys - rendering 2 duplicate items in a list- how to avoid same key warning as same items are intended without using index as key?"