Prior to React 16, multiple top-level elements in the same render()
would require you to wrap everything in a parent element (typically a <div>
):
render () {
return (
<div>
<Thing1 />
<Thing2 />
</div>
)
}
React 16 introduced the ability to render an array of top-level elements (with a warning that they all must have unique keys):
render () {
return ([
<Thing1 key='thing-1' />,
<Thing2 key='thing-2' />
])
}
React 16.2 introduced the <Fragment>
element, which functions exactly like the <div>
in the first example but doesn't leave a pointless parent <div>
hanging around the DOM:
import React, { Fragment } from 'react'
...
render () {
return (
<Fragment>
<Thing1 />
<Thing2 />
</Fragment>
)
}
There's a shorthand syntax for it, but it isn't supported by most tooling (e.g., syntax highlighters) yet:
import React from 'react'
...
render () {
return (
<>
<Thing1 />
<Thing2 />
</>
)
}
` would still need a wrapper. Furthermore it arises in nested scenarios, e.g. `
{lines.map(line => ({line}
` would still need a wrapper even if there was a top-level `))}
`. So apparently with any context switch from JavaScript to embedded JSX, the JSX portion must return a single node. See my question https://stackoverflow.com/q/75783783 .
– Garret Wilson Mar 19 '23 at 19:55