Borislav Hadzhiev
Fri Apr 29 2022·2 min read
Photo by Alexey Demidov
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.
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.
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.
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.
However, note that if you have to pass a key
prop to a fragment, you would
have to use the more verbose syntax.
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.
div
.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.
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.
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.