0

I getting this error:

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

It's my object:

class NumberColumn extends Component {
  _getNumbers() {
    let numbers = []
    let i = 0

    while (i < 10) {
      numbers.push(<div>{i}</div>)
      i++
    }

    return numbers
  }

  render() {
    const { current } = this.props

    return (
      <div className="vote__column">
        <Motion
          style={{y: spring(current * 10)}}
        >
          {({y}, i) =>
            <div
              key ={i}
              style={{
                transform: `translateY(${-y}%)`
              }}
            >
              {this._getNumbers()}  
            </div>
          }
        </Motion>
      </div>
    )
  }
}

Where should i assigne key prop?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Piotr Żak
  • 2,046
  • 5
  • 18
  • 30
  • What does you `this._getNumbers` function return? – Tholle Jul 30 '18 at 19:29
  • It's returns number in Vote :) – Piotr Żak Jul 30 '18 at 19:30
  • 1
    Could you include the entire component in your question? – Tholle Jul 30 '18 at 19:32
  • Check these other answers as well, they really have a good explanation about the key, [**link**](https://www.google.co.in/search?q=Each+child+in+an+array+or+iterator+should+have+a+unique+%22key%22+prop+site:stackoverflow.com&rlz=1C5CHFA_enIN785IN785&sa=X&ved=2ahUKEwil0syIysfcAhUMYo8KHY1UC4YQrQIoBDAAegQIAhAM&biw=1440&bih=803) – Mayank Shukla Jul 30 '18 at 19:43

2 Answers2

1

Each element in an array used for rendering should have a key prop.

You can use the index of each element as key in the array you return from _getNumbers.

Example

_getNumbers() {
  let numbers = []
  let i = 0

  while (i < 10) {
    numbers.push(<div key={i}>{i}</div>)
    i++
  }

  return numbers
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • Where should i add key in this example. Please only advice i need to learn how to do it correctly :) const Result = ({ state: { products, displayCategory} }) =>
    {products .filter(({ category }) => displayCategory === category || displayCategory === "all" ) .map(({ category, name, StartDate, EndDate, BtcGoal, BtcDonated, desc, img}) => )}
    ;
    – Piotr Żak Jul 30 '18 at 19:40
  • @PiotrŻak Please read the piece of documentation I linked in the answer. Every element in an array used for rendering should have a unique key, so `ResultItem` in that case should have a key. – Tholle Jul 30 '18 at 19:42
  • I trying make it in this form: .map(({index, category, name, StartDate, EndDate, BtcGoal, BtcDonated, desc, img}) => )} But it's still erroring – Piotr Żak Jul 30 '18 at 19:47
-1

Each div should have it's own unique key:

<Motion
  style={{y: spring(current * 10)}}
>
  {({y}, i) =>
    <div
      key={i}
      style={{
        transform: `translateY(${-y}%)`
      }}
    >
      {this._getNumbers()}
    </div>
  }
</Motion>
Chase DeAnda
  • 15,963
  • 3
  • 30
  • 41