Pak Long
Pak Long

Reputation: 107

Why Does React DevTools Show the key for <Fragment> but Not for <li> Elements Inside a Mapped List?

In my React component, I have two mapped lists, each with key assigned:

  1. The outer list maps over recipes, using <Fragment key={recipe.id}>

  2. The inner list maps over ingredients, using <li key={ingredient}>{ingredient}</li>

However, when inspecting the component using React DevTools, I can only see the key for the <Fragment> (recipe ID), but not for the <li> elements (ingredient keys).

According to the React documentation documentation:

JSX elements directly inside a map() call always need keys!

In my case, both Fragment's and li's key are placed inside their respective map().

Why does React DevTools display the key for <Fragment> but not for <li>? Is the key for <li> still being used internally by React? Or I simply misplaced it?

my code dev tool

I tired to move the <li> inside <Fragment>, the DevTool simply ignored the <li> altogether. my code 2 dev tool2

Repo

Upvotes: 1

Views: 50

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196217

The react dev tools show only components. Not the actual DOM elements.

Fragment is a component and so it will show it along with its key.

On the other hand, the li elements inside IngredientList are not components so they are not displayed there at all.


You are correct to pass a key for the li elements though, as that is used internally by react.

Upvotes: 2

Related Questions