Render JSX Without Wrapper DOM Element In React

August 14, 2020 by Andreas Wik

JSX without wrapper DOM element

 

In React, we have to wrap the JSX we render in a parent element, often a div. Consider this:

return (
    <div>
        <p>My tiny component</p>
    </div>
)

 

Now, in the browser this will obviously render a paragraph inside of a div. This additional DOM element, the div, feels really superfluous and it would be great to avoid it.

To avoid cluttering the DOM with all these wrapper divs, we can use something called fragments. Replace the root element of your JSX with an empty tag to declare the fragment:

return (
    <>
        <p>My tiny component</p>
    </>
)

 

Now only a Paragraph element will be created in the DOM. Sweet.

 

It’s worth noting that the above is a shorthand syntax. Previously you had to declare it with <React.Fragment> and </React.Fragment>

return (
    <React.Fragment>
        <p>My tiny component</p>
    </React.Fragment>
)

 

Take care!

Share this article

Recommended articles