Simplifying React Development: The Power of Fragments

The Problem: Adjacent JSX Elements

When building a user interface with React, breaking down the UI into components is a significant advantage. However, this approach can lead to a common problem: returning sibling elements without a parent.

Consider the following example:

function MyComponent() {
  return (
Hello World!
Farewell World!

  );
}

This code will result in an error: “Adjacent JSX elements must be wrapped in an enclosing tag.”

The Solutions: Wrapping Elements and Arrays

One option is to wrap the elements with a parent element:

function MyComponent() {
  return (
Hello World!
Farewell World!

  );
}

This method introduces an extraneous element into the DOM, adding an extra level of nesting that’s not necessary.

Another option, introduced in React v16.0, is to return an array of elements:

function MyComponent() {
  return [
Hello World!
,
Farewell World!
,
  ];
}

While this approach works, it requires adding commas between elements and can produce a key warning.

A Cleaner Solution: React Fragments

React v16.2 introduced a cleaner solution: using Fragments. This approach eliminates the need for keys, array commas, and extraneous DOM elements.

You can import Fragment to avoid writing out React.Fragment, or use the shorthand syntax <> for a more concise and cleaner code:

import React, { Fragment } from 'eact';

function MyComponent() {
  return (
Hello World!
Farewell World!

    
  );
}

// or

function MyComponent() {
  return (
    <>
Hello World!
Farewell World!

    
  );
}

The Benefits of Fragments

Fragments have become a widely adopted solution in the JavaScript ecosystem. In the last two years, React, TypeScript, Babel, Prettier, and eslint-plugin-react have all added support for Fragments.

Upgrading your dependencies will likely enable you to use Fragments without additional configuration.

Leave a Reply