Why JSX Can Have Only One Parent Element

Why JSX Can Have Only One Parent Element

Is JSX really a requirement for React?

I am sure every one of us have come across this error at least once in our development journey. Or this error:

Have you ever wondered why JSX expressions must have one parent element? Let's find out.

JSX stands for JavaScript XML. It is an extension of JavaScript that allows developers to use HTML-like syntax in JavaScript code. This extension makes the composition of components easier to read as it looks like an HTML code made up of HTML elements and React elements. JSX is a syntactic sugar for React.createElement, which is a function that takes three arguments: the tag, the props, and the children. JSX is compiled back to normal JavaScript, which the browser understands.

So for example:

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

So what happens when we have multiple elements is that we have multiple return statements:

We're trying to return two things at a time, but this is not valid JavaScript. We cannot return two items at a time. So, we can only return one parent, and that parent can have as many children and grandchildren as it wants.

Solution

  • Add a parent div

    Wrapping the elements in a parent element will solve the problem.

    However, an extra div appears here which might be unnecessary.

  • Use React.fragment

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

    <> and </> is the shorthand for React.Fragment.

If you want to play around with a transpiler, Babel has a nice playground to try out things.

So as we can see JSX is not really a requirement for using React. It just really simplifies things and gives a better developer experience.

Docs: https://legacy.reactjs.org/docs/react-without-jsx.html