React Fragments: In react, whenever you want to render something to the screen. You should use the render method inside your component. This render method can return one or more elements. The Render method only renders one root node at a time. However, if you want to return multiple items, you need a “div” tag in the render method and put the content or items inside it. This extra node to the DOM can lead to malformed HTML output and is frowned upon by many developers.
Example
// Rendering with div tag
class App extends React.Component {
render() {
return (
//Extraneous div element
<div>
<h2> Hello World! </h2>
<p> Welcome to the TechieBundle. </p>
</div>
);
}
}
To solve this, ReactJS Fragments were introduced with React 16.2 version to remove the need to define an extra <div> tag which also takes extra memory.
Syntax
<React.Fragment>
<h2> child1 </h2>
<p> child2 </p>
.. ..... .... ...
</React.Fragment>
Example
// Rendering with fragments tag
class App extends React.Component {
render() {
return (
<React.Fragment>
<h2> Hello World! </h2>
<p> Welcome to the TechieBundle. </p>
</React.Fragment>
);
}
}
Why do we use React Fragments?
The main reason to use the Fragments tag is:
- It makes the execution of code faster as compared to the div tag.
- It takes less memory.
Implementation Using React Fragments
Consider an example. If you need to render multiple components, you have two options: pack the components into a div or use a react fragment.
import { Header , Footer, SideBar, Feed } from ‘./Components’
function App() {
return (
<>
<Header />
<>
<Sidebar />
<Feed />
</>
<Footer />
</>
);
}
}
export default App;
Advantages of using Fragments
React Fragment replaces the <div> element, which can cause issues with invalid HTML, with the following advantages.
- The code readability of React Fragment is higher.
- Because React fragments have a smaller DOM, they render faster and use less memory.
- React Fragment allows React components to be rendered as intended without causing any parent-child relationship issues.
- Fragments allow the return of multiple JSX elements, which addresses the issue of invalid HTML markups within react applications that were caused by the must-have constraint of only one element returning per component.
Shorthand of Fragments
We can also use <>, instead of React. Fragment but this shorthand syntax does not accept key attributes.
Example
import React from 'react';
class App extends React.Component {
render() {
return (
<>
<h2>Hello World!</h2>
<p>Welcome to the TechieBundle</p>
</>
);
}
}
export default App;
Also, read | React Refs | How to use React References