skip to Main Content

So according to the docs, React fragment does not appear on DOM. It doesn’t inject any elements to the DOM.

But let’s say we want to render elements in a loop whose inside a fragment

elementList.map((eachEl) => <> {<span></span>} </>)

There is a warning in the console "Each child in a list should have a unique "key" prop ". If you assign key to the each element, the warning does not go away.

elementList.map((eachEl) => <> {<span key={uniqeKeyValue} ></span>} </>)

If we assign a key to the fragment, the warning goes away.

So, since React fragment does not inject any elements to the DOM, why does it needs a unique key attribute? It looks like assigning key to the each element should be okay.

Why a "ghost element" that doesn’t even appear and settled on the DOM needs a unique key?

3

Answers


  1. Well, the key is not actually needed for the element itself, but for the loop (map loop in your case).

    Why is the key useful? So react can know if an element in the list was changed/moved, which one and can also apply optimizations to it and mount/unmount callbacks.

    Even though the fragment itself is not rendered, its children are. The fragment is just a logical container.

    Read this answer for more info: Understanding unique keys for array children in React.js

    Login or Signup to reply.
  2. React needs keys to efficiently update the virtual DOM and reconcile changes between the previous and current states of components. When rendering elements in a loop, each element should have a unique key to help React identify and track them properly. Even though React fragments don’t directly render any elements to the DOM, they are still considered as part of the virtual DOM structure. Assigning a unique key to the fragment helps React accurately track its identity and efficiently manage its updates.

    To resolve this issue, you can use fragments in the following way:

    import {Fragment} from 'react';
    elementList.map((eachEl) => <Fragment key={uniqueKeyValue}><span></span></Fragment>)
    

    This way, you ensure that each span element within the fragment has a unique key assigned to it, addressing the warning about unique "key" props in a list.

    Login or Signup to reply.
  3. elementList.map((eachEl) => <> {<span key={uniqeKeyValue} ></span>} </>)
    

    if you look at this line, the outermost item is <> not <span>. React is looking for keys on the outermost elements in the list.
    Here is example code to solve problem.

    elementList.map((eachEl) => <span key={uniqeKeyValue}></span>)
    

    or you can do like this as well

     elementList.map((eachEl, index) => (
      <React.Fragment key={index}>
        <span></span>
      </React.Fragment>
      ))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search