Last updated: Apr 6, 2024
Reading time·3 min
The React.js error "JSX expressions must have one parent element" occurs when a component returns multiple elements.
To solve the error, wrap the elements in a parent div
element or use a
fragment.
Here is an example of how the error occurs.
export default function App() { // ⛔️ JSX expressions must have one parent element. return ( <h2>One</h2> <h2>Two</h2> ); }
The issue in the example above is that the App
component returns multiple
elements.
One way to solve the error is to use a React fragment.
export default function App() { return ( <> <h2>One</h2> <h2>Two</h2> </> ); }
Fragments are used when we need to group a list of children without adding extra nodes to the DOM.
You might also see the more verbose syntax of fragments being used.
import React from 'react'; export default function App() { return ( <React.Fragment> <h2>One</h2> <h2>Two</h2> </React.Fragment> ); }
The two examples above achieve the same result - they group the list of child elements without adding extra nodes to the DOM.
An alternative solution is to wrap your child elements in another DOM element,
e.g. a div
.
export default function App() { return ( <div> <h2>One</h2> <h2>Two</h2> </div> ); }
This solves the error because instead of returning multiple elements, we now
return a single div
element that contains multiple children.
div
doesn't break your layout, otherwise use a fragment, because fragments don't add any extra markup to the DOM.You might also see the error occur in conditionals if one of the code paths returns multiple elements at the same level.
export default function App() { return ( <div> {/* ⛔️ JSX expressions must have one parent element.ts(2657) */} {true ? ( <h2>One</h2> <h2>Two</h2> ) : null} </div> ); }
The truthy path of the ternary operator returns 2 elements at the same level, which caused the error. We can get around this by wrapping the two elements with a fragment.
export default function App() { return ( <div> {true ? ( <> <h2>One</h2> <h2>Two</h2> </> ) : null} </div> ); }
Now each code path of the ternary returns a single value.
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('h2', null, 'One'); return React.createElement('h2', null, 'Two'); }
The second return
statement is unreachable and this is invalid syntax.
An alternative approach that you might see is to group the elements into an array.
export default function App() { return [<h2 key={0}>One</h2>, <h2 key={1}>Two</h2>]; }
The array is a single value, so the error is resolved, however, we are required
to pass a
unique key
prop to
each array element.
This is unnecessary and should be avoided as the fragment syntax is much more readable and intuitive.
export default function App() { return ( <> <h2>One</h2> <h2>Two</h2> </> ); }