/    /  ReactJS- React Fragments

React Fragments

 

We know that we make use of the react render method inside a react component whenever we want to render something to the screen. We may react render a single element or multiple elements, though rendering multiple elements will require a ‘div’ tag around the content as the render method will only render a single root node inside it at a time.

Example:

App.js:

import React from "react";

// Simple rendering with div
class App extends React.Component {
render() {
       return (
       // Extraneous div element
       <div>
               <h2>Hello</h2>

               <p>How you doin'?</p>
       </div>
       );
}
}

export default App;

OUTPUT:

fragments

Reason to use Fragments: The above react code when we are trying to react render more than one root element we have to put the entire code inside the HTML ‘div’ tag which is not loved, by some developers. So in React 16.2 version, Fragments are newly introduced, and we use them instead of the extraneous ‘div’ tag.

Syntax:

<React.Fragment> 
    <h2>Child-1</h2> 
    <p> Child-2</p> 
</React.Fragment>

App.js:

import React from "react";

// Simple rendering with fragment syntax
class App extends React.Component {
render() {
       return (
       <React.Fragment>
            <h2>Hello</h2>

            <p>How you doin'?</p>
       </React.Fragment>
       );
}
}

export default App;

OUTPUT:

fragments

 

Shorthand Fragment:

Syntax:

<> 
     <h2>Child-1</h2> 
     <p> Child-2</p> 
</>

Example:

import React from "react";

// Simple rendering with short syntax
class App extends React.Component {
render() {
       return (
       <>
                <h2>Hello</h2>

                <p>How you doin'?</p>
       </>
       );
}
}

export default App;

OUTPUT:

fragments