Learning ReactJS from 0 – Advance – P4 – Fragments

Tram Ho

Fragments

Fragments are one of React’s most basic components, which allows Component to return multiple elements at once by gathering all the children in a DOM node.

Motivation

We will come up with a specific example as follows

With the above example, Component <Column /> will have the task of returning multiple td elements at once and if not using Fragment, we will handle how, inherently React’s render function only returns 1 element for a Component

If we render like that, React will report an error and cannot run.

To solve this problem, we will think of a plan to wrap all the children into a Div tag like the <Column /> component.

It looks ok, guys, but something’s not right here.

We will get the following result:

This result is really good to run, simply because we have the wrong structure of the Table , it will not accept Div cards in tr cards.

In cases like these, Fragment is the solution that helps us solve this problem.

Usage

We can use fragment to wrap the following components:

Or can be imported as this

And the result when using Fragment will be different than we use the Div tag

Short Syntax

For convenience in coding we can use Short Syntax, and it looks like a blank tag

But note a bit, when you use short syntax, it will not support attribues and keys, so need to consider when using.

Keyed Fragments

Fragment with full syntax declaration will support key and some attributes. If you use it in mapping collection, you should use fragment with full syntax to apply key, this will make the app’s performance increase.

Conclusion

In this article, we have learned about React’s problem when rendering multiple child elements at once and how to solve that problem using Fragment.

Share the news now

Source : Viblo