1

I have the following data:

const huntersData = [
    {
        id: 1,
        name: 'A',
        image: '',
    },
    {
        id: 2,
        name: 'B',
        image: '',
    },
    {
        id: 3,
        name: 'C',
        image: '',
    },
    {
        id: 4,
        name: 'D',
        image: '',
    }
]

export default huntersData

and the following component:

import React from 'react'

export default function Hunters(props) {
    return (
        <div>
            {
                props.hunters.map(hunter => (
                    <div key="{hunter.id}" onClick={() => props.selectHunter(hunter)}>
                        <img src={hunter.image} alt={hunter.name} height="90" />
                        <p>{hunter.name}</p>
                    </div>
                ))
            }
        </div>
    )
}

and call it with:

<Hunters
    hunters={this.state.hunters}
    selectedHunter={this.state.selectedHunter}
    selectHunter={this.selectHunter}
/>

but I get the following error: Encountered two children with the same key, {hunter.id}. I even tried with using index as key but still getting the same error. The keys are unique according to the data object, what am I doing wrong?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Alex
  • 65
  • 7
  • Possible duplicate of [What do curly braces mean in JSX (React)?](https://stackoverflow.com/questions/43904825/what-do-curly-braces-mean-in-jsx-react) – Emile Bergeron Sep 05 '19 at 15:29

1 Answers1

9

You used a string literal "{hunter.id}" which is always the same. You need to use the actual id as the key:

key={hunter.id}

If you intended to use a format string the correct syntax would be:

key={`${hunter.id}`}

but this is not required here as the key is just consisting of the id itself.

trixn
  • 15,761
  • 2
  • 38
  • 55