React Fragments
React Fragments
The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM.
In React, if you want to render something to the screen, you have to use a render method within the component; and this render method will render a single root node in it at a time. But if you want to return multiple statements, then we have to put the <div> tag inside the render method and need to put the entire content and elements in it. This extra node in the DOM sometimes results in the wrong formatting of your HTML output. To solve it, React introduced the concept of Fragments.
Syntax:
child1
child2
……………..
Example
Without Using Fragment
import React, { Component } from 'react'; import { render } from 'react-dom'; class App extends React.Component { render() { return ( //Extraneous div element); } } export default App;Example of Without Using Fragment
Hello World!!.
Output:
With Fragment
import React, { Component } from 'react'; import { render } from 'react-dom'; class App extends React.Component { render() { return ( //Fragment tag); } } export default App; Example of Using Fragment
Hello World!!.
Output:
Why Fragments
There are the following reasons that make fragments valuable.
- It makes the code execution faster as compared to the <div> tag.
- It consumes less memory.
Fragments short Syntax
The main reason for using the fragments is that it is a bit faster when compared with the <div> tag.
Fragment short syntax is the shorthand for declaring the fragments. It is like an empty tag. Instead of using React.Fragment, we use <>....</> for declaring the fragments.
Example:
The following example is showing how to use fragments short syntax.
import React, { Component } from 'react'; import { render } from 'react-dom'; class App extends React.Component { render() { return ( //Fragment short syntax tag <>Fragment Short syntax Example
Hello World!! .
> ); } } export default App;
Output:
Keyed Fragments
The shorthand syntax of the fragment doesn't accept the key attributes. You require a key to map a collection to an array of fragments like to create a description list. If you want to provide keys, you need to declare the fragments with explicit <React.Fragment> syntax.
The key is the only attribute that can be passed with the fragments.
Function = (props) { return ({props.items.data.map(item => ( // Without the 'key', React will give a key warning ) }))} {item.name}
{item.url}
{item.description}