Reputation: 2023
So, I learn React in Depth and now I'm studing on React Fragments. As it described in official docs https://reactjs.org/docs/fragments.html , Fragments are very interesting way to return multiple elements. But I cannot figure out than it is better than the usual component and the transfer of the child through it?
Upvotes: 0
Views: 570
Reputation: 1988
The basic need for fragments is to avoid the usage of an extra parent wrapper that is simply present to cover up it's children. Consider an example below:
return (
<div>
<h1>Hello World!</h1>
<h2>Enjoy your life!</h2>
</div>
);
Now, one can argue that there is no need for that extra div
and he/she would rather prefer removing it. This is where fragments
come into picture. It adds the ability to remove the parent wrapper and pass in the children as an array from the return statement. With fragments, the above code would transform into:
return (
<>
<h1>Hello World!</h1>
<h2>Enjoy your life!</h2>
</>
);
Upvotes: 2
Reputation: 1788
In this React problem, you can find descriptions of some other uses: https://github.com/facebook/react/issues/2127
It's as simple as when you do not need a shell element, you do not have to use it. If you take into account fewer elements, but I think the biggest advantage is that they can display elements in jsx that were not previously possible, and add a better semantic value to the shell elements, because now they are optional.
It was impossible before:
<span>
{this.renderOptions ()}
</span>
Looking at the next in React 15, you can not determine whether the wrapper element is needed or not:
<span>
<h1> Hello </ h1>
{this.getContent ()}
</span>
Upvotes: 6