ReactJS Tutorial

Understanding ReactJS Fragments and its uses

What are Fragments in React?

Fragments in ReactJS are a modern syntax that add multiple elements to a React Component without wrapping them in an extra DOM node.

No extra elements are produced in the DOM when you use ReactJS Fragments. It allows you to group multiple sibling components without introducing any unnecessary markup in the rendered HTML.

Syntax 

Child-1    

Child-2 

Example

import React from "react";

// Simple rendering with fragment syntax

class App extends React.Component {

render() {

return (

Hello

How you doin'?

);

}

}

export default App;

Output

Reactjs fragments

Why Use Fragments?

  • Faster execution of code in comparison to the div tag.

  • Occupies less memory.

  • Allows you to write cleaner and readable code.

Fragments Short Syntax

A shorthand also exists for creating React fragments. It does the job a little bit faster as compared to the one with the ‘div’ tag inside it, as we do not create a DOM node. Another shorthand also exists for the above method in which we make use of ‘<>’ and ‘</>’ instead of the ‘React.Fragment’.

Syntax

<>  

      <h2>Child-1</h2>   

      <p> Child-2</p> 

</>

Example

//Rendering with short syntax   

class Columns extends React.Component {   

  render() {   

    return (   

      <>    

        <h2> Hello World! </h2>   

        <p> Welcome to the JavaTpoint </p>   

      </>   

    );   

  }   

}  

It’s Quiz Time!

quiz-img
Did you find this article helpful?