React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components, and those components only got rendered when I enclosed them into a single div or returned the elements as an array.
We get an error of ‘Adjacent JSX elements must be wrapped in an enclosing tag’. Thus we change our code to:
class Parent extends Component{ render(){ return( <div> <h1>Hello, world!</h1>, <h2>It is {this.props.date.toLocaleTimeString()}.</h2> </div> ) } }
This extra div element in our DOM (document object model) often causes problems when we design our components.
The other way round to render these child components is to return an array of elements that the React will then render easily without the use of another <div>.
class Parent extends React.Component{ render(){ return [ <Child/>, <Child/> ]; } }
Returning the elements as an array turned out to be a bad developer experience.
Thus to our rescue came the new feature to react that solved the problem, this feature is Fragments.
Let’s understand this concept of React Fragments.
What is React Fragment?
We solve our problem by wrapping our components into Fragments.
class Parent extends Component{ render(){ return( <React.Fragment> <Child/> <Child/> </React.Fragment> ) } }
So Fragment gave us the functionality of wrapping the Child elements/components without using an extra div element in our DOM.
We have a choice of using the Fragments in a new way.
class Parent extends Component{ render(){ return( <> <Child/> <Child/> </> ) } }
We observe that <> and </> JSX elements are short notation of <React.Fragment> and </React.Fragment> respectively.
The Problem we Encountered…..
I found the React Fragment useful when I was working with forms.
While building a login form for my social networking site, I had to return form input elements to my parent form.
Using the div tag to enclose my elements turned out to be a tough task while designing the form. Thus I switched to React Fragment.
Let’s understand this situation with an example:
I have made a different component for my input element (of type email) and I call this component inside my LoginForm component. Thus the equivalent of this code will be
<form> <input type='email' placeholder='Enter Email'/> </form>
So the Fragment made our work easier by not inserting an extra div element into the DOM and we can easily design our form.
Conclusion
Using Fragment in my projects has made it a lot easier to design my components. Now you have a proper understanding of why the React Fragment was introduced and which kind of problem it solves. We can also use the React Fragment when returning a group of elements, conditional rendering a group of elements, and working with tables. We learned an important concept and I hope you will start using React Fragment in your projects. Find out Fragment in React documentation.