Soleil
Soleil

Reputation: 7287

in react key prop is stripped

I am generating a list of TSX elements with:

    this.productsModel = this.state.products.map(o => (
            <Grid.Column key>

However, react warns me:

Warning: Each child in a list should have a unique "key" prop.

So with the recommended practice [1] I add:

    this.productsModel = this.state.products.map((o, i) => (
            <Grid.Column key={i}>

But key={i} is stripped out at rendering, whatever is the element (Grid.Column, div etc). How comes? How to solve this?

[1] https://reactjs.org/docs/lists-and-keys.html#keys

Upvotes: 1

Views: 341

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

key element is not supposed to be passed to the DOM, its a reserved props for React optimization only

So when you add key like

  this.productsModel = this.state.products.map((o, i) => (
        <Grid.Column key={i}>

The key is not even passed to the Grid.Column component but stripped by read while actually passing all the props

You also need to provide a unique key for the elements returned from within the map function

Key is provided for react to keep track of elements being rendered, so that if an element is deleted or the list is sorted, it need not re-mount everything but compares the correct elements during its virtual DOM comparison. In this way it actually improves performance

Using indexes a keys doesn't provide much of a benefit even though the warning is removed. It better you use a unique id from each product object within your products array as key

Upvotes: 2

Related Questions