Fragment in React.js || example of Fragment

Rmag Breaking News

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;

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 />
</>
);
}

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.

Leave a Reply

Your email address will not be published. Required fields are marked *