What is React fragment?

Hi, in this post we are going to learn about the React fragment that is very common in regular React Apps.

If we want to render 2 elements “side by side” inside of the “root” without a parent div like this:

  <div id="root">
   <div class="parent"> {/* without this div */}
      <div class="container">Hello</div>
      <div class="container">bye</div>
    </div>
  </div>

Just to be like this:

  <div id="root">
    <div class="container">Hello</div>
    <div class="container">bye</div>
  </div>

So, maybe will be something like:

    const element = (
      <Message greeting="Hello" subject={10} />
      <Message greeting="Bye" subject={10} />
    )

But that will be a problem because JXS will mark this as red issue and will say: “JSX expressions must have one parent element”

Or if instead of the element variable:

ReactDOM.render(element, document.getElementById('root'))

We are thinking to insert directly the <Message /> component like this below example.

Well this isn’t make any sense either:

Ok, maybe we could think to have something like this, but also we are not including the other element (the “Bye”) so we can’t insert 2 things side by side with this way:

   const element = React.createElement(Message, {
      subject: 'Hello',
      greeting: 'Cristina',
    })

Or maybe someone is thinking create the element variable as array type like this:

And technically that’s going to work but we are going to get a “warning console”:

At the end that solution is not ergonomic.

So, here is where React Fragment come and solve this situation when we want to have 2 elements “side by side” without adding a new “node to the DOM” (<div class=”parent”></div>)

    const element = (
      <React.Fragment>
        <Message greeting="Hello" subject="Cristina" />
        <Message greeting="Bye" subject="Cristina" />
      </React.Fragment>
    )

    ReactDOM.render(element, document.getElementById('root'))

View:

This solution is really use-full when the DOM structure is super important, when we are making flex-box, grid or a table.

Nice, there is a special syntax that we can use for <React.Fragment> and will be compiled as same, so the syntax that we can use could be:

<> ….</>

By Cristina Rojas.