What is a React Fragment?

Keeping the DOM Tree Clean

Have you ever inspected a React site and wondered why there are a ridiculous amount of nested divs? It would be a nightmare to later target these elements.

<div id="root">
    <!-- Why? -->
    <div>
        <!-- Seriously? -->
        <div>
            <h1>Title</h1>
            <!-- This is not okay. -->
            <div>
                <hr>
                <h2>Subtitle</h2>
                <p>Example description text content goes here...</p>
            </div>
        </div>
    </div>
</div>

This is because for every JSX component, only one element can be returned. So over time, if we're not careful we will eventually pollute the DOM tree. This is where React Fragment comes in and it's very simple.

// instead of this
import React from "react"
import Child from "./Child"

const ExampleComponent = () => {
    return (
        {/* Specified element will render */}
        <div>
            <h1>I'm the Child component</h1>
            <ExampleChild />
        </div>
    )
}

export default ExampleComponent

// do this
import React from "react"
import Child from "./Child"

const ExampleComponent = () => {
    return (
        {/* Unspecified element will NOT render ~ React.Fragment */}
        <>
            <h1>Title</h1>
            <ExampleChild />
        </>
    )
}

export default ExampleComponent

Keeping Relationships Under Control

Not only does it prevent unnecessary elements from rendering, but it allows you to control parent-child relationships.

<div id="root">
    <!-- h1, hr, h2, and p are now siblings -->
    <h1>Title</h1>
    <hr>
    <h2>Subtitle</h2>
    <p>Example description text content goes here...</p>
</div>

I will say this can potentially break any styles that were dependant on the previous DOM tree, so be careful!

Other Ways React Fragment is Used

You might also see this used in different ways, to keep in mind.

// React.Fragment
import React from "react"
import Child from "./Child"

const ExampleComponent = () => {
    return (
        <React.Fragment>
            <h1>Title</h1>
            <ExampleChild />
        </React.Fragment>
    )
}

export default ExampleComponent

// Destructuring Fragment from React
import React, { Fragment } from "react"
import Child from "./Child"

const ExampleComponent = () => {
    return (
        <Fragment>
            <h1>Title</h1>
            <ExampleChild />
        </Fragment>
    )
}

export default ExampleComponent
Copyright © 2020. Jake Birkes