React Fragments: Grouping Elements Without Extra DOM Nodes

Learn how to use React Fragments to group multiple elements in your JSX without adding unnecessary nodes to the DOM. This tutorial explains the benefits of using fragments for cleaner HTML and improved performance, covering both the long and short syntax options.



React Fragments: Grouping Elements Without Extra DOM Nodes

The Problem with Multiple Elements

In React, the `render()` method of a component can return only a single top-level element. If you need to return multiple elements, you traditionally wrapped them in a container element (like a `

`). This extra container element can sometimes clutter your HTML structure and isn't always desirable.

Rendering with Extra Div

render() {
  return (
    <div> {/* Unnecessary div */}
      <p>Hello World!</p>
      <p>Welcome to JavaTpoint</p>
    </div>
  );
}

React Fragments to the Rescue

React Fragments, introduced in React 16.2, solve this problem. They allow you to group multiple elements without adding extra nodes to the DOM. This results in cleaner HTML and can slightly improve performance.

Fragment Syntax

Long Form

Long Form Fragment Syntax

render() {
  return (
    <React.Fragment>
      <p>Hello World!</p>
      <p>Welcome to JavaTpoint</p>
    </React.Fragment>
  );
}

Short Form

An even shorter syntax is available:

Short Form Fragment Syntax

render() {
  return (
    <>
      <p>Hello World!</p>
      <p>Welcome to JavaTpoint</p>
    <>
  );
}

Why Use Fragments?

  • Improved performance (slightly faster than using a div).
  • Reduced memory usage.
  • Cleaner HTML structure.

Keyed Fragments

The short syntax (`<> `) doesn't allow the `key` prop. If you need keys (for example, when mapping over an array), you must use the long form (``).

Keyed Fragment Example

const MyComponent = (props) => (
  <React.Fragment>
    {props.items.map(item => (
      <div key={item.id}>
        <p>{item.name}</p>
        <p>{item.url}</p>
        <p>{item.description}</p>
      </div>
    ))}
  </React.Fragment>
);

Note: The `key` prop is the only attribute you can pass directly to a fragment.

Next Topic: React Router