1

I have the following stateless function in my React/Redux project:

const ListItem = props => {
    return (
        <li className={props.item.expand ? 'expanded' : ''}>
            <img src={`https://someUrl`+props.item.image}
                 alt="Illustration"
                 //onLoad={props.showImage.bind({}, props.item.id)}
                 className={props.item.showIllustration ? 'show' : ''}/>
            <h3 className="title">{props.item.title}</h3>
            <p className="date">
                {moment(props.item.date, "YYYY-MM-DD").format('DD/MM/YY')}
            </p>

            <h3 className="amount">{props.item.amount}</h3>
            <button onClick={props.showItem.bind({}, props.item.id)}>
                {props.item.show ? 'Close' : 'Info'}
            </button>

            {props.item.show ? <ItemDetails id={props.item.id} /> : ''}
        </li>
    )
}

It works well. BUT... when I uncomment the //onLoad line, the console outputs the following error:

Warning: Each child in an array or iterator should have a unique "key" prop.

I don't understand why it's asking a unique key, if already set it on the parent component:

listItems.map(element => {
    return (
        <ListItem
            key={element.id}
            element={element}
        />
    )
})

Besides, the error only is shown where I uncomment the event line. What is causing the error, and how can I fix it?

Captain
  • 105
  • 1
  • 15
  • https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js/43892905#43892905 this can help you. – Varit J Patel Nov 23 '18 at 06:16
  • @varit05 I've just read it, but actually I haven't find the answer. The problem only happens when I add the "onLoad" event on the . In fact, when I move that event to other tag, (like

    for instance), it renders normally without error at all

    – Captain Nov 23 '18 at 22:49
  • can you please create this issue on codesandbox.io? – Varit J Patel Nov 24 '18 at 02:41
  • What is the purpose of the `showImage` callback? Including that code could go a long way in helping the community help you. – Drew Reese Nov 24 '18 at 03:25

2 Answers2

0

Its required to have the key attribute on the top-most element in your rendered items, which is li in this case. The reason is because ListItem may be the parent, but its just a syntactic placeholder for the actual html elements in its render method.

Therefore you must change to the following:

<li key={props.id} className={props.item.expand ? 'expanded' : ''}>
Shawn Andrews
  • 1,432
  • 11
  • 24
  • I've already tried adding the key prop into the
  • item, but it keeps throwing the error. Another strange thing is that the error only throws when I add the "onLoad" prop.
  • – Captain Nov 23 '18 at 14:05