React fragments: What and Why

React fragments were a feature released in React 16.2. They have been around for a while now but have been a relatively lesser used feature. Let us explore the what and why the feature exists.

What are React Fragments?

React fragments are a syntax addition to React that allow wrapping or grouping of multiple HTML elements without the need for any additional DOM nodes. We mostly come across this situation when a React component needs to return multiple elements.

- Advertisement -

The traditional approach has been to wrap them in a div element because a React component can return only one element. This behavior results in useless additional markup and also makes the DOM tree heavy with additional layers of divs.

The traditional solution to render 3 child components in a single component would have been:

const App = () => {
  return (
    <div>
      <ChildA />
      <ChildB />
      <ChildC />
    </div>
  );
}

With fragments, this can be:

const App = () => {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}
React.Fragment can also be replaced by empty tags as <></> as well and that works too.
const App = () => {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}

Why React fragments?

There are 3 typical use cases for fragments.

1. Returning groups of elements

This one is the typical use case for fragments. As discussed above, using fragments avoids additional div containers that can make the DOM heavy and also often cause problems when styling things.

2. Conditional rendering

Fragments make it easier to conditionally render groups of elements without any extra markup.

const Login = ({isLoggedIn, name}) => {
    {isLoggedIn ? (
        <>
          <h3>Welcome {name}</h3>
          <p>
            You are logged in!
          </p>
        </>
      ) : (
        <>
          <h3>Login</h3>
              <input type="text" id="username" />
              <input type="password" id="password" />
              <input type="submit" value="Login" />
        </>
      )}
}

3. Rendering arrays with keyed fragments

Fragments can have key props! This is yet another powerful feature which can be pretty handy at times. This cannot be used with the empty tags though.

This can be helpful when rendering lists, such as:

const Glossary = ({items}) => {
  return (
    <>
      {items.map(item => (
        // Without the `key`, React will fire a key warning
        <React.Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))}
    </>
  );
}

Advantages

  • React fragments are a but faster and have little lesser memory consumption (lesser DOM nodes). This is helpful in applications with deep tree structures.
  • Styling can be easier at times since there is no additional div created. Sometimes some libraries depend on parent child relationships, and the div in the middle causes layout issues.
  • The DOM is easier to inspect because of less clutter.

And that is all there is to know about React fragments!

Recent Articles

How to check if a string contains emojis in JavaScript?

If you have user-generated content in your web application, chances are you have to deal with strings containing emojis. Since emojis are...

Writing conditionals in CSS: when/else

CSS already has had conditionals in the form of @media queries or @support queries to selectively apply styling to the document. But...

Retrieving content value of ::after or ::before in JavaScript

For the following element:#element::after { content: 'Custom value' }If we needed a way of...

How to permanently remove a file from Git history

We all make mistakes sometimes. Pushing files that contain some secrets or sensitive information to a Git repository is fairly common. And...

Select all text on click using CSS

When a user has to select some text on a website, they have to drag and hold their mouse, or use double-click...

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.