What’s Fragment in ReactJs
in this article, I will show you what’s Fragment in React and how and when we use it with a helpful example.
Fragment: A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes (<div>…) to the DOM.
there are 3 ways to add fragments in ReactJs:
1-import {Fragment } from ‘react’ and call it as Component<Fragment></Fragment>
2-add the component Fragment from React (<React.Fragment ></React.Fragment>)
3-add tag <></>
let’s move to the example and show you the difference between with and without using React.Fragment in the child component.
with the first example we will create two component App and child (without using fragment) :
this is the result of the above code, the child component will influence the table’s structure due to the <div> tag :
to fix this problem, we have just one solution is to add a Fragment tag in the child component, like this :
the structure of the table will be fixed after adding the Fragment tag and this how the result looks like :
I think this is helpful and the best way to understand Fragment in ReactJs.