Learnitweb

Keyed Fragment in React

In React, keyed fragments are a way to assign a key to a React.Fragment, which is useful when rendering a list of fragments inside a loop.

What is a Fragment?

A Fragment lets you group multiple elements without adding extra nodes to the DOM. It looks like this:

<>
  <div>Item 1</div>
  <div>Item 2</div>
</>

This is equivalent to:

<React.Fragment>
  <div>Item 1</div>
  <div>Item 2</div>
</React.Fragment>

What is a Keyed Fragment?

A keyed fragment is a fragment with a key prop. It’s used when you are rendering a list of fragments inside a loop, and React needs to differentiate between them.

const items = ['Apple', 'Banana', 'Cherry'];

function ItemList() {
  return (
    <div>
      {items.map((item, index) => (
        <React.Fragment key={item}>
          <h2>{item}</h2>
          <p>Delicious fruit</p>
        </React.Fragment>
      ))}
    </div>
  );
}

Why use keyed fragments?

  • You avoid adding unnecessary wrapper elements like <div> for layout purposes.
  • You still provide a key, which React uses for efficient reconciliation during re-renders.
  • It’s especially useful when your UI structure needs to be flat (e.g., when you can’t nest elements because of CSS or semantic rules).