What is React Fragment and why do JSX elements must have one parent element?

What is React Fragment and why do JSX elements must have one parent element?

React Fragment

It's a special kind of React component which allows you to position two elements side-by-side rather than just nested.

return(
  <div>
    <div>Hello</div>
    <div>World</div>
  </div>
)

The above code can be written using Fragment as:

return(
  <React.Fragment>
    <div>Hello</div>
    <div>World</div>
  </React.Fragment>
)

This is useful when the DOM structure is super important, for example when you are working on flexbox, grid, or table.

There is a new, shorter syntax you can use for declaring fragments. It looks like empty tags:

return(
  <>
    <div>Hello</div>
    <div>World</div>
  </>
)

You can use <></> the same way you’d use any other element except that it doesn’t support keys or attributes.

Why do JSX elements must have one parent element?

When you position two elements side-by-side without parent element, React will shout at you JSX element must have one parent element.

const element = (
  <div>Hello</div>
  <div>World</div>
)

ReactDOM.render(element, document.getElementById('root');

Here what you have to understand is, JSX is compiled to javascript using babel, and here the element variable can't be compiled to javascript because the syntax for creating an element in javascript won't take multiple arguments.

Instead, we can pass the arguments as the children of the parent element

const element = (
  <>
    <div>Hello</div>
    <div>World</div>
  </>
)

ReactDOM.render(element, document.getElementById('root');

The compiled code will look like this:

React.createElement(React.Fragment, null,
  React.createElement("div", null, "Hello"),
  React.createElement("div", null, "World")
);

Here, the two div are the children of React Fragment.

That's it, folks! Thanks for Reading.