Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Use One Component to Render Many HTML Fragments in React

Jun 16, 2020 • 10 Minute Read

Introduction

A typical React component is expected to return multiple JSX elements. Fragments in React allow you to return multiple child elements without populating unnecessary nodes to the DOM. This is in line with React's component architecture, and it also enhances performance in complex and deeper apps.

This guide explores an easy approach to render many HTML elements in React.js through React fragments.

Fragments in React

Before React 16.2, you could render only a single DOM node inside the render method. Now you can render multiple DOM nodes. In order to do this, wrap it inside a parent div which essentially makes it a single DOM node with multiple elements inside it. Fragments in React do not deviate much from their literal meaning. When rendering DOM elements in a component, a fragment allows you to group together your DOM elements inside a pseudo wrapper. This wrapper, the fragment itself, is not regarded as a DOM node.

Wrapper Rendering

Consider the following code snippet :

      class Countries extends React.Component {
  render() {
    return (
      <li>Canada</li>
      <li>Australia</li>
      <li>Norway</li>
      <li>Mexico</li>
    )
  }
}
    

If you run this code in React, you'll get an error: Syntax error: Adjacent JSX elements must be wrapped in an enclosing tag. React sees your render method trying to output multiple DOM nodes and bars you from doing so by throwing this error.

Modify the above code like this and you'll notice that the error goes away.

      class Countries extends React.Component {
  render() {
    return (
    <div className="country-names">
      <li>Canada</li>
      <li>Australia</li>
      <li>Norway</li>
      <li>Mexico</li>
    </div>
    )
  }
}
    

The way out is making use of a wrapper div or span element that acts as the enclosing tag. Essentially, React sees the render method outputting a single DOM node with multiple child elements inside.

Using Fragments

Creating an Empty Project

Make sure you have Nodejs and npm installed in your machine (at least version 8 or higher), along with a code editor and a web browser (preferably Chrome or Firefox).

Create a new project using create-react-app:

      npx create-react-app react-read-more
    

Cleaning up the Template

Remove the logo, App.css, and all their imports from App.js. Clean out the starter template inside the App component. Your App.js should look like this:

      import React from 'react';
import './App.css';

function App() {
  return(
      <div className="App">
     </div>
  )
}

export default App;
    

Note: Sometimes removing App.css might land you an error. In such cases, instead of deleting the App.css, keep it empty, or if you have already deleted it, create a blank CSS file under the same name in the root directory.

Setting up a Development Server

Inside the root directory, run :

      npm start
    

This will spin up a local development server (usually on port 3000) and you can see all your changes live in the browser.

Rendering Multiple JSX Elements Using Fragments

Wrap your JSX in an enclosing <React.Fragment> tag .

      import React from 'react';
import './App.css';

function App() {
  return (
    <React.Fragment>
      <li>ReactJS</li>
      <li>AngularJS</li>
      <li>VueJS</li>
      <li>Bootstrap</li>
    </React.Fragment>
    
  );
}

export default App;
    

Fragments Shorthand Syntax

You can avoid the React.Fragment keyword and simply contain your fragment's content inside a pair of <> </>. This is a shorthand syntax for fragments, as shown below .

      import React from 'react';
import './App.css';

function App() {
  return (
    <>
      <li>ReactJS</li>
      <li>AngularJS</li>
      <li>VueJS</li>
      <li>Bootstrap</li>
    </>
    
  );
}

export default App;
    

Rendering Multiple HTML Fragments Through a Single React Fragment

You can render as many elements inside a fragment as child nodes that follow their regular tree structure, as the fragment itself is not a DOM node.

      import React from 'react';
import './App.css';

function App() {
  return (
    <>
      <div> This is a div 
        <h2> This is a div sub heading </h2>
      </div>
        <li>This is list item 1</li>
        <li>This is list item 2</li>
        <li>This is list item 3</li>
      <div>This is another div
        <p>some text inside div</p>
      </div>
    </> 

      
  );
}

export default App;
    

For instance, in the above example, your fragment has five parent nodes: first a <div>, followed by three <li>s, and then another <div>. Inside the <div>, you have child elements <h2> and <p>. Thus your DOM model is still maintained as a hierarchical tree.

Rendering Multiple React Fragments in a Single Component

You can embed your UI components as fragment components in a single component. Let's take a use case where you want to render a list of continents, countries, and cities. The ideal approach would be to divide these lists into separate components and then render them in their parent component. Inside the src folder, create a new folder, components, and create the following components:

Continents.js

This component renders a list of continents inside a fragment.

      import React from 'react';

const Continents=()=>{
    return(
        <React.Fragment>
            <li>Asia</li>
            <li>Austrailia</li>
            <li>Antarctica</li>
        </React.Fragment>
    )
}

export default Continents;
    

Countries.js

This component renders a list of countries inside a fragment.

      import React from 'react';

const Countries=()=>{
    return(
        <React.Fragment>
            <li>India</li>
            <li>China</li>
            <li>Germany</li>
        </React.Fragment>
    )
}

export default Countries;
    

Cities.js

This component renders a *ist of cities inside a fragment.

      import React from 'react';

const Cities=()=>{
    return(
        <React.Fragment>
            <li>Mumbai</li>
            <li>Bengaluru</li>
            <li>Kolkata</li>
        </React.Fragment>
    )
}

export default Cities;
    

Finally, import all the components and render them inside App.js.

      import React from 'react';
import './App.css';
import Continents from './components/Continents';
import Countries from './components/Countries';
import Cities from './components/Cities';

function App() {
  return (
    <>
      <Continents></Continents>
      <Countries></Countries>
      <Cities></Cities>
    </> 
  );
}

export default App;
    

Instead of creating separate components, you can also put it all together in one component.

      import React from 'react';
import './App.css';

const Continents=()=>{
  return(
      <React.Fragment>
          <li>Asia</li>
          <li>Austrailia</li>
          <li>Antarctica</li>
      </React.Fragment>
  )
}

const Countries=()=>{
  return(
      <React.Fragment>
          <li>India</li>
          <li>China</li>
          <li>Germany</li>
      </React.Fragment>
  )
}

const Cities=()=>{
  return(
      <React.Fragment>
          <li>Mumbai</li>
          <li>Bengaluru</li>
          <li>Kolkata</li>
      </React.Fragment>
  )
}

function App() {
  return (
    <>
     <Continents></Continents>
     <Countries></Countries>
     <Cities></Cities>
    </> 
  );
}

export default App;
    

Now you have used essentially a single component to render many HTML fragments. Thus, fragments also help you organize your code better, make it more modular without the need for an extra parent node every time you're grouping some DOM elements together.

Advantages of Fragments

Let's look at why fragments were introduced and their obvious advantages .

Faster

Using fragments is a tad bit faster, which becomes evident for component trees extending deep in your frontend's architecture.

Consume Less Memory

Imagine one less parent wrapper for every fragment in a large app that used hundreds of components and even more embedded inside them. It makes a considerable performance difference for such an application, rendering it light-weight and resulting in smoother user experience.

Error-Free CSS

Modern CSS structures for positioning and containing elements like flexbox and grid rely on their special parent-child relationship. Adding unnecessary additional divs can often give unwanted results or make it difficult to design what you intend to. Even those CSS frameworks that depend heavily on flexbox layouts like Bootstrap can offer some discrepancies while utilizing those mechanisms. Fragments ensure that your design layouts lay intact, just as they're supposed to be.

Modularity

Breaking down code into modular fragments is more logical. It keeps your HTML/JSX concise, clean, and less messy. This also makes debugging HTML and CSS easier on both the editor and the inspector .

Conclusion

As a developer, you can benefit from the urge to learn new features and adopt good coding practices. React 16.2 offers a number of exciting updates that can make your development process faster and less cumbersome. Through this guide, you learned what fragments are and how to use them to render multiple HTML fragments inside a single component.