Ben
Ben

Reputation: 107

Why am i getting a unique key prop warning when i have a unique key?

import React from 'react';
import User from '../containers/User';
import './Sidebar.css';


const Sidebar = ({ contacts }) => {
return(
  <aside className="Sidebar">
      {contacts.map(contact => <User user={contact} key= 
      {contact.user_id} /> )}
   </aside>
 );
};

export default Sidebar;

I have a key for the User and i still get this warning and dom is not rendering the contacts.Any help would be appreciated.Thanks in advance

Upvotes: 1

Views: 111

Answers (4)

Ben
Ben

Reputation: 107

Yeah the id has been duplicated.I found and got rid of it. Thank you guys!!!

Upvotes: 0

Ji aSH
Ji aSH

Reputation: 3457

As people said, it is likely that one of your userIds is duplicated.

To get rid of the warning you can build the key differently (but then you will loose some react optimization)

import React from 'react'
import User from '../containers/User'
import './Sidebar.css'

const Sidebar = ({ contacts }) => {
  return(
    <aside className="Sidebar">
      {contacts.map((contact, index) => <User user={contact} key={`${index}-${contact.user_id}`} />)}
    </aside>
  )
}

export default Sidebar

Upvotes: 0

Darshan
Darshan

Reputation: 131

I couldn't see any mistake in the code posted regarding the key.

But there is a chance that the user_id passed in the contacts itself is duplicated, so that unique key warning might be appearing.

Irrespective of that warning, dom should be rendered as its a warning not an error. So, for not rendering the dom there might be some other problems like User component not returning anything or like wise..

I tried locally with the Sidebar component shared, which worked fine. If there is a fiddle for the problem it would be easy to identify the root cause.

Upvotes: 1

Anil Kumar
Anil Kumar

Reputation: 2309

Check this working example using your code. Hope it helps.

https://codesandbox.io/s/5w5v287lj4

import React from "react";
import User from "./User";

 const Sidebar = ({ contacts }) => {
  return (
   <div>
  {contacts.map(contact => (
    <User user={contact} key={contact.id} />
  ))}
</div>
);
 };

export default Sidebar;

<Sidebar contacts={contacts} />

import React from "react";

const User = ({ user }) => {
 return <div>{user.id}</div>;
};

export default User;

Upvotes: 0

Related Questions