Author avatar

Gaurav Singhal

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

Gaurav Singhal

  • Jun 16, 2020
  • 10 Min read
  • 130 Views
  • Jun 16, 2020
  • 10 Min read
  • 130 Views
Web Development
Front End Web Development
Client-side Framework
React

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 <div> Rendering

Consider the following code snippet :

1
2
3
4
5
6
7
8
9
10
class Countries extends React.Component {
  render() {
    return (
      <li>Canada</li>
      <li>Australia</li>
      <li>Norway</li>
      <li>Mexico</li>
    )
  }
}
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Countries extends React.Component {
  render() {
    return (
    <div className="country-names">
      <li>Canada</li>
      <li>Australia</li>
      <li>Norway</li>
      <li>Mexico</li>
    </div>
    )
  }
}
jsx

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:

1
npx create-react-app react-read-more
shell

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:

1
2
3
4
5
6
7
8
9
10
11
import React from 'react';
import './App.css';

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

export default App;
jsx

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 :

1
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 .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
jsx

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 .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';

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

export default Continents;
jsx

Countries.js

This component renders a list of countries inside a fragment.

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';

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

export default Countries;
jsx

Cities.js

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

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';

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

export default Cities;
jsx

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
jsx

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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;
jsx

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.

2