React v16.2.0: Improved Support for Fragments
This blog site has been archived. Go to react.dev/blog to see the recent posts.
React 16.2 is now available! The biggest addition is improved support for returning multiple children from a component’s render method. We call this feature fragments:
Fragments look like empty JSX tags. They let you group a list of children without adding extra nodes to the DOM:
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
This exciting new feature is made possible by additions to both React and JSX.
What Are Fragments?
A common pattern is for a component to return a list of children. Take this example HTML:
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
Prior to version 16, the only way to achieve this in React was by wrapping the children in an extra element, usually a div
or span
:
render() {
return (
// Extraneous div element :(
<div>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</div>
);
}
To address this limitation, React 16.0 added support for returning an array of elements from a component’s render
method. Instead of wrapping the children in a DOM element, you can put them into an array:
render() {
return [
"Some text.",
<h2 key="heading-1">A heading</h2>,
"More text.",
<h2 key="heading-2">Another heading</h2>,
"Even more text."
];
}
However, this has some confusing differences from normal JSX:
- Children in an array must be separated by commas.
- Children in an array must have a key to prevent React’s key warning.
- Strings must be wrapped in quotes.
To provide a more consistent authoring experience for fragments, React now provides a first-class Fragment
component that can be used in place of arrays.
render() {
return (
<Fragment> Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</Fragment> );
}
You can use <Fragment />
the same way you’d use any other element, without changing the way you write JSX. No commas, no keys, no quotes.
The Fragment component is available on the main React object:
const Fragment = React.Fragment;
<Fragment>
<ChildA />
<ChildB />
<ChildC />
</Fragment>
// This also works
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
JSX Fragment Syntax
Fragments are a common pattern in our codebases at Facebook. We anticipate they’ll be widely adopted by other teams, too. To make the authoring experience as convenient as possible, we’re adding syntactical support for fragments to JSX:
render() {
return (
<> Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</> );
}
In React, this desugars to a <React.Fragment/>
element, as in the example from the previous section. (Non-React frameworks that use JSX may compile to something different.)
Fragment syntax in JSX was inspired by prior art such as the XMLList() <></>
constructor in E4X. Using a pair of empty tags is meant to represent the idea it won’t add an actual element to the DOM.
Keyed Fragments
Note that the <></>
syntax does not accept attributes, including keys.
If you need a keyed fragment, you can use <Fragment />
directly. A use case for this is mapping a collection to an array of fragments — for example, to create a description list:
function Glossary(props) {
return (
<dl>
{props.items.map(item => (
// Without the `key`, React will fire a key warning
<Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</Fragment>
))}
</dl>
);
}
key
is the only attribute that can be passed to Fragment
. In the future, we may add support for additional attributes, such as event handlers.
Live Demo
You can experiment with JSX fragment syntax with this CodePen.
Support for Fragment Syntax
Support for fragment syntax in JSX will vary depending on the tools you use to build your app. Please be patient as the JSX community works to adopt the new syntax. We’ve been working closely with maintainers of the most popular projects:
Create React App
Experimental support for fragment syntax will be added to Create React App within the next few days. A stable release may take a bit longer as we await adoption by upstream projects.
Babel
Support for JSX fragments is available in Babel v7.0.0-beta.31 and above! If you are already on Babel 7, simply update to the latest Babel and plugin transform:
# for yarn users
yarn upgrade @babel/core @babel/plugin-transform-react-jsx
# for npm users
npm update @babel/core @babel/plugin-transform-react-jsx
Or if you are using the react preset:
# for yarn users
yarn upgrade @babel/core @babel/preset-react
# for npm users
npm update @babel/core @babel/preset-react
Note that Babel 7 is technically still in beta, but a stable release is coming soon.
Unfortunately, support for Babel 6.x is not available, and there are currently no plans to backport.
Babel with Webpack (babel-loader)
If you are using Babel with Webpack, no additional steps are needed because babel-loader will use your peer-installed version of Babel.
Babel with Other Frameworks
If you use JSX with a non-React framework like Inferno or Preact, there is a pragma option available in babel-plugin-transform-react-jsx that configures the Babel compiler to de-sugar the <></>
syntax to a custom identifier.
TypeScript
TypeScript has full support for fragment syntax! Please upgrade to version 2.6.2. (Note that this is important even if you are already on version 2.6.1, since support was added as patch release in 2.6.2.)
Upgrade to the latest TypeScript with the command:
# for yarn users
yarn upgrade typescript
# for npm users
npm update typescript
Flow
Flow support for JSX fragments is available starting in version 0.59! Simply run
# for yarn users
yarn upgrade flow-bin
# for npm users
npm update flow-bin
to update Flow to the latest version.
Prettier
Prettier added support for fragments in their 1.9 release.
ESLint
JSX Fragments are supported by ESLint 3.x when it is used together with babel-eslint:
# for yarn users
yarn add [email protected] babel-eslint@7
# for npm users
npm install [email protected] babel-eslint@7
or if you already have it, then upgrade:
# for yarn users
yarn upgrade [email protected] babel-eslint@7
# for npm users
npm update [email protected] babel-eslint@7
Ensure you have the following line inside your .eslintrc
:
"parser": "babel-eslint"
That’s it!
Note that babel-eslint
is not officially supported by ESLint. We’ll be looking into adding support for fragments to ESLint 4.x itself in the coming weeks (see issue #9662).
Editor Support
It may take a while for fragment syntax to be supported in your text editor. Please be patient as the community works to adopt the latest changes. In the meantime, you may see errors or inconsistent highlighting if your editor does not yet support fragment syntax. Generally, these errors can be safely ignored.
TypeScript Editor Support
If you’re a TypeScript user — great news! Editor support for JSX fragments is already available in Visual Studio 2015, Visual Studio 2017, Visual Studio Code and Sublime Text via Package Control.
Other Tools
For other tools, please check with the corresponding documentation to check if there is support available. However, if you’re blocked by your tooling, you can always start with using the <Fragment>
component and perform a codemod later to replace it with the shorthand syntax when the appropriate support is available.
Installation
React v16.2.0 is available on the npm registry.
To install React 16 with Yarn, run:
yarn add react@^16.2.0 react-dom@^16.2.0
To install React 16 with npm, run:
npm install --save react@^16.2.0 react-dom@^16.2.0
We also provide UMD builds of React via a CDN:
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
Refer to the documentation for detailed installation instructions.
Changelog
React
- Add
Fragment
as named export to React. (@clemmy in #10783) - Support experimental Call/Return types in
React.Children
utilities. (@MatteoVH in #11422)
React DOM
- Fix radio buttons not getting checked when using multiple lists of radios. (@landvibe in #11227)
- Fix radio buttons not receiving the
onChange
event in some cases. (@jquense in #11028)
React Test Renderer
- Fix
setState()
callback firing too early when called fromcomponentWillMount
. (@accordeiro in #11507)
React Reconciler
Internal Changes
- Many tests were rewritten against the public API. Big thanks to everyone who contributed!
Acknowledgments
This release was made possible by our open source contributors. A big thanks to everyone who filed issues, contributed to syntax discussions, reviewed pull requests, added support for JSX fragments in third party libraries, and more!
Special thanks to the TypeScript and Flow teams, as well as the Babel maintainers, who helped make tooling support for the new syntax go seamlessly.
Thanks to Gajus Kuizinas and other contributors who prototyped the Fragment
component in open source.