Understanding Fragments in React: What, Why and How

If you are a React developer, and haven’t heard of React Fragments yet, this post if for you. React Fragments is a feature that was introduced a while ago in React 16.2.0. But it is not as popular as it should be. In this post, we learn about what React Fragments are, how to use it and why it is a great feature. Let’s dive in right away.

What Are React Fragments ?

If you have been a React developer for a while, you would have probably run into a situation like this before:

import React from "react";

export default () => (
    <h1>Hello I am heading one </h1>
    <h1>Hey there I am another heading </h1>
);

This piece of React code will return the following error **_Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. _**I have encountered this error many times and I know that a React component with multiple elements need to be wrapped in something like a _

. _

The code then gets transformed into:

import React from "react";

export default () => (
    <div>
      <h1>Hello I am heading one </h1>
      <h1>Hey there I am another heading </h1>
    </div>
);

Adding a <div> to enclose the multiple elements gets rid of the error. This happens all across the code, whenever a component returns multiple elements, we end up enclosing it with a <div>.

This requirement by React results in a number of unwanted markupall across the DOM and is hard to debug. Sometimes it may even result in invalid HTML to be rendered.

Here is where React Fragments come in. The same piece of code can now be updated using a React Fragment, instead of the unnecessary

.

**React Fragments can group a list of children without adding extra nodes to the DOM. **This is a much need addition in React, because now you can just use React Fragments, which don’t render in the DOM, instead of using real elements like <div>.

import React from "react";

export default () => (
    <React.fragment>
      <h1>Hello I am heading one </h1>
      <h1>Hey there I am another heading </h1>
    </React.fragment>
); 

In the example above you can see that we don’t see the error anymore, and we are not rendering the additional

. Instead we are using fragments which are like invisible elements to wrap the components.

Example of Rendering Invalid HTML

Let’s look at a classic example, where adding

to enclose components with multiple elements can actually result in an invalid HTML. The best example for this would be using a Table Component below:

class TableComponent extends React.Component {
  render() {
    return (
      <table>
        <tr>
          <HeaderComponent />
        </tr>
        <tr>
          <td>Adhithi Ravichandran/td>
          <td>React Fragments</td>
          <td>100</td>
        </tr>
      </table>
    );
  }
}

In this example above, we have created a TableComponent that renders a table with a header and some content. Now the header for the table is another component called _HeaderComponent. _Let’s create a simple _HeaderComponent _for the table.

class HeaderComponent extends React.Component {
  render() {
    return (
        <th>Author Name</th>
        <th>Blog Post Title</th>
        <th>Likes</th>
    );
  }
}

// error: Adjacent JSX elements must be wrapped in an enclosing tag.

By the looks of it, the component looks right, I want it to return three header columns. But, React is going to throw an error “_Adjacent JSX elements must be wrapped in an enclosing tag.” _Well, now if went with the old approach of just adding a _

_around this component, it is going to return an invalid HTML.

Invalid HTML

class HeaderComponent extends React.Component {
  render() {
    return (
      <div>
        <th>Author Name</th>
        <th>Blog Post Title</th>
        <th>Likes</th>
     </div>
    );
  }

// error goes away, but this results in invalid HTML

In this case we have added

enclose the elements, but it will result in a random div in the middle of a table’s HTML. This is actually an invalid HTML. This is a perfect example to use the React Fragment instead.

Updated Code With Fragments

class HeaderComponent extends React.Component {
  render() {
    return (
      <React.Fragment>
        <th>Author Name</th>
        <th>Blog Post Title</th>
        <th>Likes</th>
      </React.Fragment>
    );
  }

With the above code, now our HeaderComponent just returns three table headers for each column, and the fragment is invisible and not a part of the DOM. This makes debugging the DOM easier, and removes any unnecessary clutter.

React Fragments Short Syntax

The fragments can also be used with a short syntax instead of calling out React.Fragments all the time. An empty tag and and empty closing tag can be used as a short syntax for fragments.

class HeaderComponent extends React.Component {
  render() {
    return (
      <>
        <th>Author Name</th>
        <th>Blog Post Title</th>
        <th>Likes</th>
      </>
    );
  }

**Note: **With the short syntax, you cannot assign a key or attribute to the element.

This brings up a point about keys. You can pass keys as an attribute to your fragment, when you don’t use the short syntax. This is useful when you have an array of fragments. And keys are currently the only attribute that can be passed to a fragment.

Conclusion

In this post, we learned about React Fragments.

  • React Fragments can be used whenever there are multiple elements, and they need to be wrapped in an enclosing tag.
  • This is an alternate to using
    when they are not necessary, just to get rid of the error thrown by React.
  • Fragments are invisible and do not get added on to the DOM.
  • The DOM nodes are less cluttered with one less element, each time you add a fragment instead of a div.
  • Fragments can take in keys as an attribute.

#React #JavaScript #WebDev #react-js

Understanding Fragments in React: What, Why and How
6.10 GEEK