Fragment in react
Created on: Aug 31, 2024
In React, a Fragment is used to group a list of children elements without adding extra nodes to the DOM. This is particularly useful in scenarios where you want to return multiple elements from a component but don’t want to introduce unnecessary wrapping elements like <div>, which can clutter the DOM and cause styling or layout issues.
The output of using div and React.Fragment is same but the main reason for using is that it is a tiny bit faster when compared to the one with the ‘div’ tag inside it, as we didn’t create any DOM node.Also, it takes less memory.
Shorthand for using React.Fragment is <> </>
For example in below code,
import React from "react"; class App extends React.Component { render() { return ( <div> <h2>Hello World</h2> <p>How you you</p> </div> ); } } export default App;
We have we have h2 and p tags which needs div tag to wrap. This add extra node as shown below.
Let's change the code and add fragment and see the change.
import React from "react"; class App extends React.Component { render() { return ( <React.Fragment> <h2>Hello World</h2> <p>How you you</p> <React.Fragment> ); } } export default App;
And updated dom is.