2

When the passed child is an array of tags I got the well known 'Each child in a list should have a unique "key" prop" react warrnig.

scenario 1:

<UnorderedList>
  {[
    <div>str 1</div>, 
    <div>str 2</div>, 
    <div>str 3</div>
  ]}
</UnorderedList>

But when the tags are no long in an array, the warrning disapperas

scenario 2:

<UnorderedList>
  <div>str 1</div>, 
  <div>str 2</div>, 
  <div>str 3</div>,
</UnorderedList>

If a key is supplied to the tags within the array (first example -> [<div key="some key supplied by the client">str 1</div>] the error would dissapear but it's very inconvenient to make the clinet supply their own keys.

The implementation of the component is the following:

export const UnorderedList: React.FC<UnorderedListProps> = ({
  children,
}) => {
  ....

  return (
    <StyledUl>
      {React.Children.map(children, child => {
        return (
          <StyledLi key={getId()}>
            {child}
          </StyledLi>
        );
      })}
    </StyledUl>
  );
};

React doc site says that React.Children.toArray() "..returns the children opaque data structure as a flat array with keys assigned to each child..". Tried it but still get the warrning.

How to get rid of the warrning while still passing the data as explained in scenario 1?

Codesandbox: https://codesandbox.io/s/exciting-gates-hgylo?file=/src/App.js Just uncomment the last piece of code

Edit2: leaving this here How to find the cause of the Warning: Each child in a list should have a unique "key" prop

pollx
  • 643
  • 9
  • 21

1 Answers1

0

Those snippets of code aren't equivalent from React perspective:

// Option 1
<UnorderedList><div>str 1</div></UnorderedList>;

// Option 2
<UnorderedList>{[<div>str 1</div>]}</UnorderedList>;

With option2, React needs to identify which items have changed, added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

That's because in runtime, React can't tell what's inside the array until it renders it, React will assign indexes as keys and give a warning for that.

On the other hand, option1 guarantees order, and its simple to follow, so no keys are needed.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118