Reputation: 1549
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
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
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
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
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