CodesJava

Easy learning with example program codes

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:

<React.Fragment>  
<h2> child1 </h2>   
<p> child2 </p>   
      .. ..... .... ...  
</React.Fragment>

Example:

class App extends React.Component {   
render() {   
return (   
<React.Fragment>  
<h2> Welcome </h2>   
<p> You are in the world of ReactJS. </p>   
</React.Fragment>  
);   
}   
}

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:

class Columns extends React.Component {   
render() {   
return (   
<>    
<h2> Welcome </h2>   
<p> You are in the world of ReactJS. </p>  
</>   
);   
}   
}

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:

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>  
)  
}
Please follow and like us:
error









Copyright © 2019 CodesJava DMCA.com Protection Status