Search code examples
javascriptreactjsreact-nativekeyreact-native-flatlist

Warning: Each child in a list should have a unique "key" prop Error in React-native


hey guys iam building a list in an app with react-native iam following a video and my code is exactly like him but for some reason i still get an error that tell me each child in the list need a key even tho iam providing one.

 function addGoalHandler() {
    setCourseGoals(currentCourseGoals => [...currentCourseGoals,
       {text:enteredGoalText,key: Math.random().toString()}]);
  };

<FlatList 
        data={courseGoals}
         renderItem={(itemData) => 
          { 
            return <Goalitem text={itemData.item.text}/>;
          }}
          keyExtractor={(item, index) =>
          {
            return item.id;
          }} /> 

this is the code that matter for the key and the list Warning: Each child in a list should have a unique "key" prop.

Check the render method of `VirtualizedList`. See https://reactjs.org/link/warning-keys for more information.
    at CellRenderer (http://192.168.1.13:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:58327:36)
    in VirtualizedList (created by FlatList)
    in FlatList (created by App)
    in RCTView (created by View)
    in View (created by App)
    in RCTView (created by View)
    in View (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)

this the error that iam getting i tried to find a solution but i couldnt so i would appreciate some help < 3

i trid to go the docs or search here for a solution but i foudn nothing that helped me


Solution

  • Problem:

    First of all you're using the id and the item doesn't have an id it has an key, In the second part you shouldn't use Math.Random

    Solution:

    to solve the issue just use the key and the index together like this:

    <FlatList 
            data={courseGoals}
             renderItem={(itemData) => 
              { 
                return <Goalitem text={itemData.item.text}/>;
              }}
              keyExtractor={(item, index) =>
              {
                return `${item.key}-${index.toString()}`;
              }} /> 
    

    Hope it helps you :D