Why do I get the following warning: Each child in a list should have a unique "key" prop

Hello,

I’m new in app development and also in Expo. So currently I’m trying to develop a simple app where the user will be able to filter some data using checkboxes. For checkboxes I have created two functions and an array, containing the relevant text for each checkbox. So far my code looks like this:

function MyCheckbox() {
  const [checked, onChange] = useState(false);

  function onCheckmarkPress() {
    onChange(!checked);
  }

  return (
    <Pressable
      style={[styles.checkboxBase, checked && styles.checkboxChecked]}
      onPress={onCheckmarkPress}>
      {checked && <Ionicons name="checkmark" size={18} color="white" />}
    </Pressable>
  );
}
const kategorieList = ["Backware", "Bioprodukte", "Feinkost", "Griechische Spezialitäten", "Molkerei", "Türkische Spezialitäten"]

{kategorieList && kategorieList.map((val, i) => {

    return <View style={styles.checkboxContainer}>

          <MyCheckbox />
                  <Text style={styles.checkboxLabel} key={i}>{val}</Text>

   </View>

})}

This code work perfectly fine but the following warning ist shown in the console: Warning: Each child in a list should have a unique “key” prop.

Can someone tell me what I’m doing wrong here.

Thank in advance

Hey @hm1995, React uses the key prop create a relationship between the component and the DOM element. This ensures that the correct child is targeted when actions such as deletion occurs. So you’ll definitely want to fix it by adding a key prop to your <View style={styles.checkboxContainer}>.

Cheers,
Adam

Hi @hm1995

As @adamjnav says it’s a way for React to keep track of the components in a list. This allows it to optimise updates. If your data has some sort of unique key (e.g. a product_id or something like that) then it would be best to use that for the key.

You have put a key in the Text component, but it does not help there, because the component that is directly inside the list is the View component, so as Adam says, that’s the component that needs the key prop.

See this for a good explanation.

@adamjnav @wodin Thank you so much for your reply. It really helped and now the warning is gone :slight_smile:

1 Like

Here’s another explanation:

EDIT: and here’s a useful reply to Dan’s tweet

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.