Fragments in ReactJS

React Fragments
React Fragments is introduced from the 16.2 and above version, to facilitate the grouping off a list of children without adding extra nodes to the DOM.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<react.fragment>
<h2> child1 </h2>
<p> child2 </p>
.. ..... .... ...
</react.fragment>
<react.fragment> <h2> child1 </h2> <p> child2 </p> .. ..... .... ... </react.fragment>
  

child1

child2

.. ..... .... ...

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class App extends React.Component {
render() {
return (
<react.fragment>
<h2> Welcome </h2>
<p> You are in the world of ReactJS. </p>
</react.fragment>
);
}
}
class App extends React.Component { render() { return ( <react.fragment> <h2> Welcome </h2> <p> You are in the world of ReactJS. </p> </react.fragment> ); } }
class App extends React.Component {   
render() {   
return (   
  

Welcome

You are in the world of ReactJS.

); } }

Importance of React Fragments:

  • The execution of code is faster with the use of React fragments as compared to the div tag.
  • Less memory is utilised with the use of React fragments as compared to the div tag.

Fragments Short Syntax:
For declaring fragments, there is another shorthand exists.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Columns extends React.Component {
render() {
return (
<>
<h2> Welcome </h2>
<p> You are in the world of ReactJS. </p>
);
}
}
class Columns extends React.Component { render() { return ( <> <h2> Welcome </h2> <p> You are in the world of ReactJS. </p> ); } }
class Columns extends React.Component {   
render() {   
return (   
<>    

Welcome

You are in the world of ReactJS.

); } }

Keyed Fragments:
In ReactJS, Key is the only attribute that can be passed with the Fragments, as it is needed for mapping a collection to an array of fragments.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Function = (props) {
return (
<fragment>
{props.items.data.map(item => (
<react.fragment key="{item.id}">
<h2>{item.brand}</h2>
<p>{item.type}</p>
<p>{item.weight}</p>
</react.fragment>
))}
</fragment>
)
}
Function = (props) { return ( <fragment> {props.items.data.map(item => ( <react.fragment key="{item.id}"> <h2>{item.brand}</h2> <p>{item.type}</p> <p>{item.weight}</p> </react.fragment> ))} </fragment> ) }
Function  = (props) {  
return (  
  
{props.items.data.map(item => (  
  

{item.brand}

{item.type}

{item.weight}

))}
) }