React
Why JSX can only have one parent element

Why JSX Can Only Have One Parent Element

Go to Twitter Post (opens in a new tab)

The Error

When you try to return multiple elements from a component, you will get an error message like this:

jsx-transform-1

How JSX Works

JSX is a syntactic sugar for React.createElement, which is a function that takes three arguments: the tag, the props, and the children.

jsx-transform-2

Nested Example

If you have a nested element, the children will be an array of React.createElement

jsx-transform-3

Why can't we return multiple elements?

If you see the example, it actually makes sense

jsx-transform-4

As we know, we can't return 2 elements from a function, so returning 2 parent elements in a component/map function is not possible.

Solutions

There are two solutions to this problem:

Wrap the elements in one parent element

By wrapping the elements in one parent element, we can solve the problem.

jsx-transform-5

However, you are ending up with an extra element in the DOM tree. This might be your desired result, and mostly it is. Use this if you want to.

Use React.Fragment

React.Fragment is a component that doesn't render anything in the DOM tree.

jsx-transform-6

If you want to return multiple elements without adding an extra element in the DOM tree, use React.Fragment.

Last updated on November 14, 2023