1. 6
    Render two elements side-by-side with React Fragments
    3m 6s

Render two elements side-by-side with React Fragments

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet

In React, you can’t render two React elements side-by-side (<span>Hello</span><span>World</span>). They have to be wrapped in another element (like a <div>). This may seem like an odd limitation, but when you think about the fact that JSX is compiled to React.createElement calls, it makes sense. In this lesson we’ll take a look at that and how to side-step this limitation with React Fragments.

smartx-fe
smartx-fe
~ 11 months ago

sorry, I dont understand. why 'JSX is compiled to React.createElement calls, so in React, you can’t render two React elements side-by-side' ?

Lauro Silva
Lauro Silva
~ 10 months ago

Hey @smartx-fe!

Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, ...children) function. The JSX code:

<MyButton color="blue" shadowSize={2}>
  Click Me
</MyButton>

compiles into:

React.createElement(
  MyButton,
  {color: 'blue', shadowSize: 2},
  'Click Me'
)

You can also use the self-closing form of the tag if there are no children. So:

<div className="sidebar" />

compiles into:

React.createElement(
  'div',
  {className: 'sidebar'}
)

If you want to test out how some specific JSX is converted into JavaScript, you can try out the online Babel compiler.