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.
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' ?
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.