Directory Image
This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Privacy Policy.

Fragments in ReactJS(v.16.2.0)

Author: Sasi Kiran
by Sasi Kiran
Posted: Mar 21, 2021

The fragment is a first-class component to wrap your child components and HTML elements instead of using any HTML element.

Normal way of wrapping child component in render method

render(){ return( Without Fragment ); }

For above example, if you will not wrap the child component using tag then you would face syntax error that the JSX element must be rendered in an enclosing tag.To understand this, Let’s think about function call, when we call the function, we can’t return more than once at a time in a function call, and we can return nothing also. So its necessary to wrap child component in an enclosing tag.

To solve above problem, React 16.0 launched a new feature for returning an array of elements from a component’s render method. Instead of wrapping the children in a DOM element, you can put them into an array. Here you can see above example

render() { return [ A heading Element, "String Element", Another heading Element, ]; }

But while we will use this feature we need to keep in mind few points like

  1. Children in an array must be separated by commas.
  2. Children in an array must have a key to prevent React’s key warning.
  3. Strings must be wrapped in quotes.

Using above approach or returning array of the element increases complexity so to make things consistent latest version of React, React v.16.2.0 has been launched the feature called Fragment. So according to the previous example in every component, we need to wrap child component in an enclosing tag like or. So if we think about whole application then we may add a lot of extra tags which will make our DOM operation expensive by adding an extra node. Using this feature of ReactJS Fragment now we can return child component without adding an extra node to the DOM.

Fragment’s way of wrapping the child component in render method

render(){ return( With Fragment ); }

We can also use empty tags instead of

render(){ return( With Fragment ); }

But if we have to pass any attribute then we can’t use the empty tags to wrap child component. Then we have to use tags to wrap child component and to pass attributes.

render(){ return( {props.list.map(item =>( {item.name} {item.description} ))} ); }

Looking for ReactJS Development Services, hire our dedicated developers!

About the Author

My sef sasi kiran, working as an digital marketer

Rate this Article
Leave a Comment
Author Thumbnail
I Agree:
Comment 
Pictures
Author: Sasi Kiran

Sasi Kiran

Member since: Feb 03, 2021
Published articles: 4

Related Articles