React Fragments and Wrapper Components

React Fragments and Wrapper Components

One of JSX limitation in React is that you have to return only one root element in each component/function.

Why React Force us to have our JSX code under 1 root element "with/without children"?

  • The Babel compiler transforms JSX into React.createElement() function
  • React.createElement accepts only one type of element as first parameter.

No alt text provided for this image
JSX into React.createElement()


Why using div as a wrapper is not a good idea in programming?

  • You may end up of unnecessary nested divs that don't add any structural meaning to your page. “<div> soup”
  • It could break your styling if you are using nested css selector
  • Rendering too many HTML elements may makes your application slower because the browser needs to render all of those elements and check if content needs to be changed

React.Fragment, better approach than the <div> container

You can wrap your JSX code with <React.Fragment> , where you don't need to create extra component

  • Fragment has less memory usage (no need to create an extra DOM node).
  • Can accept "key" attribute “the only attribute that can be passed to Fragment”
  • Cleaner, more readable code


Shorter syntax for declaring fragments is Empty tags <></> 

Empty tags can be used as any other element except that it doesn’t support keys or attributes, it was introduced in React v.16.2.0.  

No alt text provided for this image
React Fragments

In the future, React may add support for React.Fragment for additional attributes, such as event handlers.

Another way to wrap your elements without adding extra layer:

Is by using a helper component that takes props as argument and returns children

No alt text provided for this image
Wrapper component

The helper components do the same job as the fragments to return multiple JSX elements without adding extra layer , but by using  React.Fragment you don't need to create extra component so it has less memory usage.



Now you know what is the difference between <div> or any html element container , React Fragment, and helper components, you should be able to decide based on your needs which approach is better for you.

Very insightful article, Mashallah

Like
Reply

To view or add a comment, sign in

More articles by Leen Shehadeh

Others also viewed

Explore content categories