Andrew Clark 7 years ago
parent
commit
698543b5c1
  1. 63
      content/blog/2017-11-28-react-v16.2.0-fragment-support.md

63
content/blog/2017-11-28-react-v16.2.0-fragment-support.md

@ -1,5 +1,5 @@
---
title: "React v16.2.0: Fragment Support"
title: "React v16.2.0: Improved Support for Fragments"
author: [clemmy]
---
@ -19,15 +19,18 @@ render() {
}
```
This exciting new feature is made possible by new additions to both React and JSX.
## What Are Fragments?
A common pattern is for a component to return a list of children. An example is rendering some text with a link inside. Take this example HTML:
A common pattern is for a component to return a list of children. Take this example HTML:
```html
Text with
<a href="/foo">multiple</a>
<a href="/bar">links</a>
inside it.
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
```
Prior to version 16, the only way to acheive this in React was by wrapping the children in an extra element, usually a `div` or `span`:
@ -35,14 +38,14 @@ Prior to version 16, the only way to acheive this in React was by wrapping the c
```js
render() {
return (
// Extraneous span element :(
<span>
Text children
<button>interleaved</button>
with
<button>other</button>
children.
</span>
// Extraneous div element :(
<div>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</div>
);
}
```
@ -52,11 +55,11 @@ To address this limitation, React 16.0 added support for [returning an array of
```jsx
render() {
return [
"Text children",
<button key="button1">interleaved</button>,
"with",
<button key="button2">other</button>,
"children."
"Some text.",
<h2 key="heading-1">A heading</h2>,
"More text."
<h2 key="heading-2">Another heading</h2>,
"Even more text."
];
}
```
@ -73,11 +76,11 @@ To provide a more consistent authoring experience for fragments, React now provi
render() {
return (
<Fragment>
Text children
<button>interleaved</button>
with
<button>other</button>
children.
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</Fragment>
);
}
@ -112,11 +115,11 @@ Fragments are a common pattern in our codebases at Facebook. We anticipate they'
render() {
return (
<>
Text children
<button>interleaved</button>
with
<button>other</button>
children.
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</>
);
}
@ -152,7 +155,7 @@ function Glossary(props) {
### Live Demo
You can experiment with JSX fragment syntax with this [CodePen](#).
You can experiment with JSX fragment syntax with this [CodePen](https://codepen.io/reactjs/pen/VrEbjE?editors=1000).
## Support for Fragment Syntax

Loading…
Cancel
Save