Search code examples
reactjsrecursionkey

why key error Recursion component in React


i'm trying to recursion components but react key props is duplicate in root when using uuid, is fine. i don't know reason, help me

// filterModal.jsx
<FilterGroupCollection
            parentFiltergroup={parentFiltergroup}
            setParentFilterGroup={setParentFilterGroup}
            name='a'
/>
{parentFiltergroup.groups?.map((group, idx) => (
          <FilterGroupCollection
            key={name}
            parentFiltergroup={group}
            setParentFilterGroup={setParentFilterGroup}
            name={`${name}-${idx + 1}`}
          />
        ))}

enter image description here


Solution

  • It looks like you are using the same value for the key prop and that's why you are getting the key duplicate error in the console. Ideally you should use a unique key for each component, and that key could be a unique id that you get from each group. Something like this:

    {parentFiltergroup.groups?.map((group, idx) => (
     <FilterGroupCollection
       key={group.id} //notice here the id that you should get from each group
       parentFiltergroup={group}
       setParentFilterGroup={setParentFilterGroup}
       name={`${name}-${idx + 1}`}
     />
    ))}
    

    Alternatively, if you do not have any unique value inside each group, you can use the idx as key but this is not a good practice as explained by React:

    We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.

    Docs: https://reactjs.org/docs/lists-and-keys.html#keys