skip to Main Content

I am not able to get rid of it with this warning

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

Here is the complete code:

const App = () => {

  const userList = [
    {
      key: 1,
      name: "Amit"
    },
    {
      key: 2,
      name: "Ajit"
    },
    {
      key: 3,
      name: "Avinash"
    },
  ];

  return (
    <View>
      <Text style={{ textAlign: 'center' }}>Hello List</Text>
      <ScrollView>
        {
          userList.map((item) => <Text style={styles.container}>{item.name}</Text>)
        }
      </ScrollView>
    </View>
  );
};

2

Answers


  1. It says what you have to do right there in the warning.

    Add a key property to the <Text you return in the map. For example,

      return (
        <View>
          <Text style={{ textAlign: 'center' }}>Hello List</Text>
          <ScrollView>
            {
              userList.map((item) => <Text key={item.name} style={styles.container}>{item.name}</Text>)
            }
          </ScrollView>
        </View>
      );
    
    Login or Signup to reply.
  2. To avoid having this warning, you need to pass the (unique) key prop to each list item.
    You can modify you code in this way to avoid the warning:

    {
      userList.map((item) => <Text key={item.key} style={styles.container}>{item.name}</Text>)
    }
    

    Make sure not to use name or any field which is not guranteed to be unique. If two items in the list have the same name, React will not be able to uniquely identify them. This can lead to rendering issues or unexpected behavior when updating the list.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search