Avoid unnecessary DIVs when wrapping elements in React

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

Avoid unnecessary DIVs when wrapping elements in React #

Use a React fragment to avoid using unnecessary DIVs when wrapping elements in React, e.g. <><h2>Hello</h2><h2>World</h2></>. React Fragments are used when we need to group a list of children without adding extra nodes to the DOM.

App.js
const App = () => { return ( <> <h2>Hello</h2> <h2>World</h2> </> ); }; export default App;

We used a React fragment to group a list of children without adding extra nodes to the DOM.

react wrapper without div

The screenshot shows that our sibling h2 elements have been added to the DOM without being wrapped in an extra DOM node.

You might also see the more verbose syntax of fragments being used.

App.js
import React from 'react'; const App = () => { return ( <React.Fragment> <h2>Hello</h2> <h2>World</h2> </React.Fragment> ); }; export default App;

The two examples above achieve the same result - they group the list of children elements without adding extra nodes to the DOM.

The more concise syntax is more commonly used now that most code editors support it.

However, note that if you have to pass a key prop to a fragment, you would have to use the more verbose syntax.

App.js
import React from 'react'; const App = () => { const arr = ['Hello', 'World']; return arr.map(element => { return ( <React.Fragment key={element}> <h2>{element}</h2> </React.Fragment> ); }); }; export default App;
We used the more verbose syntax for React fragments to be able to add a key prop to the fragment.

If you use the shorthand syntax for fragments <> </>, you won't be able to pass any props to the fragment.

You can also import the Fragment element from react to not have to access it as React.Fragment.

App.js
// 👇️ only import Fragment import {Fragment} from 'react'; const App = () => { const arr = ['Hello', 'World']; return arr.map(element => { return ( <Fragment key={element}> <h2>{element}</h2> </Fragment> ); }); }; export default App;

This code sample achieves the same result, but instead of importing the React namespace object, we only import the Fragment element.

Use the search field on my Home Page to filter through my more than 1,000 articles.