user3808307
user3808307

Reputation: 1549

Why am I getting a warning of not having a unique key?

This is my render

render() {
    let products = this.state.products  
    return (
      <ul>
        {products.map((product, index) => Product({ key: index, product: product }))}          
      </ul>
    );
  }

I am using a unique key, and still get the warning

Warning: Each child in an array or iterator should have a unique "key" prop.

Upvotes: 0

Views: 155

Answers (4)

HPierce
HPierce

Reputation: 7409

I'm seeing this:

function Product(props) {
  return (
     <p key={props.key}>{props.product}</p> 
  )
}

function Main(props) {
  let products = [ "foo", "bar", "baz"];
  return (
    <ul>
      {products.map((product, index) => Product({key: index, product: product }))}        
    </ul>
  );
}

ReactDOM.render(
  <Main></Main>,
  document.getElementById('example')
);

and this:

function Product(props) {
  return (
     <p>{props.product}</p> 
  )
}

function Main(props) {
  let products = [ "foo", "bar", "baz"];
  return (
    <ul>
      {products.map((product, index) => (
        <li key={index}>
          {Product({product: product })}
        </li>
      ))}    
    </ul>
  );
}

ReactDOM.render(
  <Main></Main>,
  document.getElementById('example')
);

Do what you're trying to accomplish.

If I had to guess (I don't have high confidence in this explanation), I would suspect that React requires a key prop on child components to so that it can quickly determine which elements need to be re-rendered when state changes. Therefore, passing a key prop won't actually achieve anything unless it's actually rendered as UI. The two examples above are rendering keys to the virtual DOM in the <p> and <li> respectively.

Upvotes: 1

Aditya Thakur
Aditya Thakur

Reputation: 2610

You are not passing child elements to the ul

render() {
    let products = this.state.products  
    return (
      <ul>
        {products.map((product, index) => 
          <li key={index}>
            {product}
          </li>}          
      </ul>
    );
  }

Upvotes: 1

SakoBu
SakoBu

Reputation: 4011

That's not how you return a Component or pass it the key prop (or any other props...)

<ul>
    {products.map((product, index) => (
        <Product key={index} product={product} />
    ))}
</ul>

https://reactjs.org/docs/components-and-props.html#composing-components

Upvotes: 1

Ethan Moore
Ethan Moore

Reputation: 401

I found this for you.

How to create unique keys for React elements?

It seems like you need to have a return for the key. Or, as it states, npm packages already exist to declare unique keys.

Upvotes: 1

Related Questions