Return multiple elements from a React component

avatar

Borislav Hadzhiev

Fri Apr 29 20222 min read

Return multiple elements from a React component #

Use a React fragment to return multiple elements from a component, e.g. <><div>First</div><div>Second</div></>. React Fragments are used when we need to group a list of children without adding extra nodes to the DOM.

App.js
export default function App() { return ( <> <div>First</div> <div>Second</div> </> ); }

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

return multiple elements

The screenshot shows that our sibling div 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'; export default function App() { return ( <React.Fragment> <div>First</div> <div>Second</div> </React.Fragment> ); }

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'; export default function App() { const arr = ['First', 'Second']; return arr.map(element => { return ( <React.Fragment key={element}> <div>{element}</div> </React.Fragment> ); }); }

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

An alternative solution is to wrap your child elements in another DOM element, e.g. a div.
App.js
export default function App() { return ( <div> <div>First</div> <div>Second</div> </div> ); }

This solves the error because instead of returning multiple elements, we return a single div element that contains multiple children.

We have to only return a single element from a React component because it's invalid syntax to return multiple values from a function.

React components are just functions, so when we return multiple elements at the same level, we are effectively using multiple return statements at the same level of a function.

App.js
function render() { return React.createElement('div', null, 'First'); return React.createElement('div', null, 'Second'); }

The second return statement is unreachable and this is invalid syntax.

On the other hand, when we wrap the elements with a fragment or another element, the function only returns a single value with multiple child elements, which solves the error.

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