Questions
This component is crashing with a JSX syntax error. How do you fix it?
A developer is trying to create a simple ItemList component that renders a list of items. They’ve written JSX that looks like this:
function ItemList() {
return (
<li>Item 1</li>
<li>Item 2</li>
);
}
However, their code is crashing with a syntax error, typically something like “Adjacent JSX elements must be wrapped in an enclosing tag.”
The Challenge
You’ve been given the ItemList component.
- Identify the JSX syntax error.
- Fix the component to correctly render a list of items without introducing unnecessary DOM nodes.
import React from 'react';
export default function ItemList() {
// THE BUG: JSX expressions must have exactly one outermost element.
// Returning multiple sibling elements directly is a syntax error.
return (
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
);
}
function App() {
return (
<div>
<h1>My Shopping List</h1>
<ul>
<ItemList />
</ul>
</div>
);
} The Solution
export default function ItemList() { // THE BUG: JSX expressions must have exactly one outermost element. // Returning multiple sibling elements directly is a syntax error. return ( <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> ); }
export default function ItemList() { // FIX: Wrap the multiple <li> elements in a React Fragment. return ( <> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </> ); }
Why This Works
The error “Adjacent JSX elements must be wrapped in an enclosing tag” is a fundamental rule of JSX. A JSX expression must always have exactly one outermost element. You cannot return multiple sibling elements directly from a component’s render method or a JSX expression.
This rule exists because JSX is ultimately compiled into React.createElement() calls. React.createElement() can only create one element at a time. If you try to return multiple elements, it’s ambiguous which one should be the “root” of that particular createElement call.
The Fix: Wrapping with a Fragment
To fix this, you need to wrap the multiple sibling elements in a single parent element. The most common and semantically correct way to do this without adding an extra, unnecessary DOM node is to use a React Fragment.
A React Fragment allows you to group a list of children without adding extra nodes to the DOM. You can use React.Fragment explicitly or, more commonly, the shorthand syntax <>...</>.
By wrapping the <li> elements in a Fragment, we satisfy the JSX rule of having a single root element without introducing an extra div that might interfere with styling or semantic HTML (especially important when rendering lists or table rows).
Practice Question
What does JSX compile down to?