DEV Community

Cover image for Do not use <div> in ReactπŸ˜ŽπŸ˜―πŸ‘©β€πŸ’»
Nayan Kaslikar
Nayan Kaslikar

Posted on

Do not use <div> in ReactπŸ˜ŽπŸ˜―πŸ‘©β€πŸ’»

Howdy People,πŸ˜πŸ™‹β€β™€οΈ
I'm on this fantastic journey where I'm exploring new & fun concepts of React.
This concept of Fragments sounds like the perfect
SHORTCUT ever πŸ€£πŸ˜‚

Fragments

We all use <div> everytime when we work in html to make containers or wrap elements inside one element.πŸ₯±πŸ˜΄

In React JSX,
To return multiple components or elements we have to wrap & group all the elements inside a wrapper like div.

But in most of the cases that div is not required at all & it takes an extra space in the DOM but still we have to use it because that's how React works.
So, react introduced a new feature in React 16.2 which are React Fragments πŸ€‘πŸ€‘πŸ€‘
Fragments

Now React Fragments works exactly like Div, you can wrap or group multiple elements with Fragments.

return(
    <React.Fragment>
        <MyComponent1 />
        <MyComponent2 />
        <MyComponent3 />
    </React.Fragment>
)
Enter fullscreen mode Exit fullscreen mode

Also you can use Fragments shorthand (<> </>) instead of React.Fragment,
example :

return(
    <>
        <MyComponent1 />
        <MyComponent2 />
        <MyComponent3 />
    </>
)
Enter fullscreen mode Exit fullscreen mode

But why to use Fragments?? πŸ€”πŸ€”πŸ€”

Fast
Div element creates a node in DOM & occupy some space, but Fragments doesn't do any of this.

Less cluttered DOM
Having many nested div makes the DOM large & hard to read or debug but with Fragments, DOM becomes a little easy to look at and debug.

Okay Bye, Hope you liked this shortcut of mine!!
Feel free to add comments & hit likes.
πŸ«‘πŸ‘Œβ­πŸ’›πŸ‘

Top comments (0)