DEV Community

Adam La Rosa
Adam La Rosa

Posted on

React Fragments

When dealing with React function or class components, everything that is returned needs to be in a wrapper element. This can be most any element tag, most commonly a

tag. As soon as you start nesting components, the elements start stacking up.
import React from 'react';
import './App.css';

function OneSuchComponent() {
  return (
    <div>
      ONE SUCH COMPONENT
    </div>
  )
}

function AnotherComponent() {
  return(
    <div>
      THIS IS ANOTHER
    </div>
  )
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        header
      </header>
      <main>
        <OneSuchComponent /><br/>
        <AnotherComponent />
      </main>
    </div>
  );
}
export default App;

Would give us the following HTML

<div id="root">
  <div class="App">
    <header class="App-header">header</header>
    <main>
      <div>ONE SUCH COMPONENT</div><br>
      <div>THIS IS ANOTHER</div>
    </main>
  </div>
</div>

If we did not want the wrapper tags included in the rendered HTML, React provides "Fragments" which would allow you to seamlessly inject components return values without the wrappers.

By including the Fragments...

import React, { Fragment } from 'react'

...then replacing the wrapper elements with tags...

function OneSuchComponent() {
  return (
    <Fragment>
      ONE SUCH COMPONENT
    </Fragment>
  )
}

function AnotherComponent() {
  return(
    <Fragment>
      THIS IS ANOTHER
    </Fragment>
  )
}

...the corresponding HTML generated by the components no longer shows a wrapper element.

<div id="root">
  <div class="App">
    <header class="App-header">header</header>
    <main>
      ONE SUCH COMPONENT<br>
      THIS IS ANOTHER
    </main>
  </div>
</div>

Top comments (1)

Collapse
 
eonyang profile image
Yang

You don’t need to import Fragment to use it.
Just wrap your elements with ‘<> </>’