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.

4 Answers

1
SakoBu On Best Solutions

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

1
Ethan Moore On

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.

1
Aditya Thakur On

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>
    );
  }
1
HPierce On

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.