Wasteland
Wasteland

Reputation: 5369

React-native - error about unique key

Why do I still get the error about needing to have a unique key? This.props.numbers is an array of numbers and they generate/display fine with the code below. I still, however, get the error: Each child in an array or an iterator should have a unique 'key' prop.

generateGrid() {
    return this.props.numbers.map((sq) =>
      <TouchableWithoutFeedback>
        <Square key={sq} style={{ height: 30, width: 30 }}>
          <Text>
            {sq}
          </Text>
        </Square>
      </TouchableWithoutFeedback>
    );
  }

Upvotes: 0

Views: 186

Answers (1)

Matt Aft
Matt Aft

Reputation: 8936

React wants you to provide a key because it optimizes how it determines whether items have changed and wouldn't have to re-render everything. Just add a key like this:

generateGrid() {
    return this.props.numbers.map((sq, i) =>
      <TouchableWithoutFeedback key={i} > //Here
        <Square key={sq} style={{ height: 30, width: 30 }}>
          <Text>
            {sq}
          </Text>
        </Square>
      </TouchableWithoutFeedback>
    );
  }

Upvotes: 1

Related Questions