React JS Tutorial-3 | React Fragments
React Fragments
In React Fragment is used to return a multiple elements inside a component.
Let’s understand this concept with an example. I had made a component named ReactFragment and I am returning Hello inside a h1 tag.
Now, I want to return my name inside another h1 tag. So, what I will do? I will write another h1 tag like the image below.
Let’s see the output on browser.
As we can see that app is crashed with an error, “Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?”
So, now I am going to show you some of way to resolve this error. And while doing so, you get to learn everything about React Fragments by the end of this blog.
If you observe the error carefully, it’s talking about a wrapping element. So. let’s wrap our h1 tag inside a div and you can see that now we are getting the expected output.
By wrapping our elements inside a div tag we had fixed this issue. But, there is one more way to fix this issue and that is React Fragments.
I had wrapped my h1 tags inside <React.Fragment>. And we got our output.
There is one short syntax for React.Fragment. The short syntax for React Fragment is an empty tag, i.e., <></>
That’s all about React Fragment. Let’s meet again in my next blog.