Jack23
Jack23

Reputation: 1396

Each child unique "key" prop

I receive this warning:

Warning: Each child in a list should have a unique "key" prop.

render() {
    const exercises = this.state.Exercises.map(exercise => {
      return (
        <View>
          <Text style={{ fontSize: 15 }}>Id: {exercise.Id} </Text>
          <Text style={{ fontSize: 15 }}>Ripetizioni: {exercise.Reps}</Text>
          <Text style={{ fontSize: 15 }}>Note: {exercise.Notes}</Text>
          <TouchableOpacity
            style={[styleButton.button, styleButton.buttonOK]}
            onPress={() => this.checkAttività(exercise.Id)}
          >

How can I solve it?

Upvotes: 0

Views: 243

Answers (3)

Tien Duong
Tien Duong

Reputation: 2595

You just need to add a unique key to your View

<View key={exercise.Id}>

Upvotes: 3

Jite
Jite

Reputation: 5847

The error message is quite clear. React wants you to define a value that is unique for each item in the list which should be assigned as a key prop to each of the View objects.

If you want, you could just pull the index out in the map loop and use that as the key:

const exercises = this.state.Exercises.map((exercise, index) => {
  return (
    <View key={`view-${index}`}>
...

Please read @JanosVinceller comment below and check the link out for a very good reason to NOT do what I propose here. At the least if it is a list which changes.

Upvotes: 2

Est&#232;ve
Est&#232;ve

Reputation: 113

You should pass a key to the return content like :

    const exercises = this.state.Exercises.map(exercise => {
      return (
        <View key={`${exercise.Id}`}>
          <Text style={{ fontSize: 15 }}>Id: {exercise.Id} </Text>
          <Text style={{ fontSize: 15 }}>Ripetizioni: {exercise.Reps}</Text>
          <Text style={{ fontSize: 15 }}>Note: {exercise.Notes}</Text>
          <TouchableOpacity
            style={[styleButton.button, styleButton.buttonOK]}
            onPress={() => this.checkAttività(exercise.Id)}
          >
      )
    })

Edit: React expect key to be a string

Upvotes: 5

Related Questions