Sergii Getman
Sergii Getman

Reputation: 4371

Encountered two children with the same key

I'm really new to react and redux development. I have a list component that is connected to a container. I want to update a list on scroll but i get:

Encountered two children with the same key

My component:

import React, { Component, PropTypes } from 'react'
import Track from './Track'
import styles from './TrackList.css'

const altImg = require('../images/sc.jpg');

export default class TrackList extends Component  {

  static propTypes = {
    tracks: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number.isRequired
      }).isRequired).isRequired,
    onTrackListScroll: PropTypes.func.isRequired
  }

 render() {
    const { tracks, onTrackListScroll } = this.props;
    return (
      <div>
      <ul className='tracks'
        onScroll={(e)=>{
          console.log('SCROLL!!',e)
          onTrackListScroll()
        }}>
        {tracks.map(track =>
          <Track
            key={track.id}
            {...track}
            //onClick={() => onTrackClick(track.id)}
            text={track.title}
            imgSrc={!track.artwork_url ? altImg : track.artwork_url}
          />
        )}
      </ul>
      </div>
    )

  }
}

reducer that update a state is :

const toSearchResultOb = (tracks) => {
  return  {
    tracks: tracks
  }
}


case 'UPDATE_SEARCH_RESULT':
      return Object.assign({}, state, 
toSearchResultOb(state.tracks.concat(action.tracks)))

What is correct way to update component onScroll with redux?

Upvotes: 1

Views: 2125

Answers (1)

Chris
Chris

Reputation: 59511

You're getting this error because keys between component siblings need to be unique. You probably have duplicate track.id in your tracks array.

Here's an easy fix:

{tracks.map(track, i =>
  <Track
    key={i}
    {...track}
    //onClick={() => onTrackClick(track.id)}
    text={track.title}
    imgSrc={!track.artwork_url ? altImg : track.artwork_url}
  />
)}

If you have a look at the documentation of map() on MDN, you'll see this:

callback Function that produces an element of the new Array, taking three arguments:

  • currentValue The current element being processed in the array.

  • index The index of the current element being processed in the array.

So in the example above, i is the index of the current element. This index increments on each iteration which guarantees unique keys within that map(). Now you don't have to worry about what track.id is.

Upvotes: 3

Related Questions