Skip to content Skip to sidebar Skip to footer

React - Each Child In An Array Or Iterator Should Have A Unique "key" Prop

I have a problem with the key props in a React JS component. I'm getting Warning: Each child in an array or iterator should have a unique 'key' prop. Check the render method of Log

Solution 1:

I don't know how your LoginForm component looks like.

But each time you iterate over an array you have to set the key prop to each of the resulting DOM element as React needs it to optimize the re-rendering. For example:

<div className="container">
        {myarray.map((element, index) => {
            return <div key={'mykey' + index}>{element}</div>;
        })}
</div>

React for example will detect duplicates and only renders the first node with this key.


Solution 2:

The reason behind this warning is that you have not passed 'key' property. React uses this property for optimizing the rendering process as in when something changes in React, a re-render will occur only for what all has changed.

If our children are dynamic and in case they get shuffled with random functions or new components are introduced in the beginning of an array, the re-render is likely to get messed up. So, assigning this 'key' property helps us make sure that the state and identity of our components is maintained through multiple renders. Please find below a sample code snippet demonstrating how to pass a key.

<MyComponent key={{item.key}}/>

The importance of key is beautifully explained here.


Post a Comment for "React - Each Child In An Array Or Iterator Should Have A Unique "key" Prop"