DEV Community

Cover image for Fragment in React.js || example of Fragment
Anil
Anil

Posted on

Fragment in React.js || example of Fragment

In React, a fragment is a lightweight syntax that allows you to group multiple children elements without adding extra nodes to the DOM. Fragments are useful when you want to return multiple elements from a component, but you don't want to wrap them in an unnecessary parent element.

Here's an example demonstrating the usage of fragments:

import React from 'react';

function App() {
  return (
    <div>
      <Header />
      <Content />
    </div>
  );
}

function Header() {
  return (
    <header>
      <h1>This is the header</h1>
      <p>Subtitle goes here</p>
    </header>
  );
}

function Content() {
  return (
    <main>
      <p>Content goes here</p>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    </main>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

In this example, the App component renders a Header and a Content component. However, the JSX returned by the App component must have a single root element. Instead of wrapping the Header and Content components inside a div, we can use a fragment to avoid adding an extra node to the DOM:

import React from 'react';

function App() {
  return (
    <>
      <Header />
      <Content />
    </>
  );
}



Enter fullscreen mode Exit fullscreen mode

In this updated version, the <>...</> syntax is a fragment. It doesn't add any extra DOM element, allowing the Header and Content components to be rendered side by side without an unnecessary parent div.

Fragments improve code readability and performance by avoiding unnecessary DOM nesting. They are especially useful when working with components that require strict DOM structures or when returning lists of elements.

Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js

Top comments (0)