gene b.
gene b.

Reputation: 11994

"Warning: Each child in a list should have a unique "key" prop " for object containing "key" attribute in array

The component MyComp takes an array of objects from which it will construct Buttons. I also provide a key for each object. In this case, 1 Button should be created from a 1-element object array:

<MyComp 
    buttons={[{"key":"approvalsButton","variant":"info","text":"Approvals Queue","url":"/approvals"}]} />

Component Definition

export default function MyComp(props) {
    return (

        <Col lg={6} className="home-tile">
            <div className="home-tile-content">
                <div className="home-tile-buttons">                 
                    {
                        /* Loop through specified Buttons (if any) and their object attributes */
                    
                        props.buttons 
                        ?                   
                            props.buttons.map(button => (
                                <LinkContainer to={button.url}>
                                    <Button key={button.key} variant={button.variant}>{button.text}</Button>
                                </LinkContainer>
                            ))
                        :
                            ''  
                    }
                </div>
            </div>
        </Col>

But I'm still getting

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

Check the render method of `MyComp`. See https://reactjs.org/link/warning-keys for more information.

Upvotes: 0

Views: 49

Answers (1)

David
David

Reputation: 218847

As the error states, the elements being rendered by map need a key property to uniquely identify them. This has nothing to do with the objects you're using or whether or not they have a property called key, this just refers to the actual component being rendered. In this case the <LinkContainer>.

In most cases you won't need to use this property, but the framework does. So in most cases you can simply use the second argument to the map callback which is the index of the collection. For example:

props.buttons.map((button, i) => (
  <LinkContainer key={i} to={button.url}>
    <Button variant={button.variant}>{button.text}</Button>
  </LinkContainer>
))

If the objects in your array do have a unique property then you can also use that just as easily:

props.buttons.map(button => (
  <LinkContainer key={button.key} to={button.url}>
    <Button variant={button.variant}>{button.text}</Button>
  </LinkContainer>
))

Upvotes: 1

Related Questions