What is a Fragment in React?

A fragment is a pattern in React that allows you to return multiple elements without having to additional HTML tags to wrap other elements. It’s a way to make the DOM less cluttered.

If you try to render a list of nodes like this:

class MyComponent extends React.Component {
    render() {
        return (
            <h1>Heading</h1>
            <p>Paragraph</p>
        )
    }
}

You will get a warning in your editor similar to this:

“JSX parent expressions must have one parent element”.

You could solve that problem by wrapping your two elements inside e.g. a div:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <h1>Heading</h1>
        <p>Paragraph</p>
      </div>
    );
  }
}

Or you can avoid adding extra elements to the DOM and instead wrap your elements inside a a fragment like this:

class MyComponent extends React.Component {
  render() {
    return (
      <React.fragment>
        <h1>Heading</h1>
        <p>Paragraph</p>
      </React.fragment>
    );
  }
}

Or use the shorthand syntax:

class MyComponent extends React.Component {
  render() {
    return (
      <>
        <h1>Heading</h1>
        <p>Paragraph</p>
      </>
    );
  }
}

By wrapping your elements with a React fragment, only what’s inside your fragment gets rendered to the DOM.

It may seem like a small thing, but all the small things add up over time. Whenever you can make your website or app take up less space, as long as you don’t hurt the accessibility and usability of your platform, then that’s a good thing!


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on