Browse Source

Doc updates for React 16 + blog post (#10824)

* Doc updates for React 16 + blog post

* Add link to Sophie's post
main
Andrew Clark 7 years ago
committed by GitHub
parent
commit
0e43ef2682
  1. 6
      _data/nav_docs.yml
  2. 209
      _posts/2017-09-26-react-v16.0.md
  3. 12
      docs/installation.md
  4. 90
      docs/portals.md
  5. 32
      docs/reference-javascript-environment-requirements.md
  6. 28
      docs/reference-react-component.md
  7. 46
      docs/reference-react-dom-node-stream.md
  8. 72
      docs/reference-react-dom-server.md
  9. 28
      docs/reference-react-dom.md

6
_data/nav_docs.yml

@ -46,6 +46,8 @@
title: Reconciliation
- id: context
title: Context
- id: portals
title: Portals
- id: web-components
title: Web Components
- id: higher-order-components
@ -65,8 +67,6 @@
title: ReactDOM
- id: react-dom-server
title: ReactDOMServer
- id: react-dom-node-stream
title: ReactDOMNodeStream
- id: dom-elements
title: DOM Elements
- id: events
@ -77,3 +77,5 @@
title: Shallow Renderer
- id: test-renderer
title: Test Renderer
- id: javascript-environment-requirements
title: JS Environment Requirements

209
_posts/2017-09-26-react-v16.0.md

@ -0,0 +1,209 @@
---
title: "React v16.0"
author: acdlite
---
We're excited to announce the release of React v16.0! Among the changes are some long-standing feature requests, including [**fragments**](#new-render-return-types-fragments-and-strings), [**error boundaries**](#better-error-handling), [**portals**](#portals), support for [**custom DOM attributes**](#support-for-custom-dom-attributes), improved [**server-side rendering**](#better-server-side-rendering), and [**reduced file size**](#reduced-file-size).
### New render return types: fragments and strings
You can now return an array of elements from a component's `render` method. Like with other arrays, you'll need to add a key to each element to avoid the key warning:
```js
render() {
// No need to wrap list items in an extra element!
return [
// Don't forget the keys :)
<li key="A">First item</li>,
<li key="B">Second item</li>,
<li key="C">Third item</li>,
];
}
```
In the future, we'll likely add a special fragment syntax to JSX that doesn't require keys.
We've added support for returning strings, too:
```js
render() {
return 'Look ma, no spans!';
}
```
[See the full list of supported return types](/react/docs/react-component.html#render).
### Better error handling
Previously, runtime errors during rendering could put React in a broken state, producing cryptic error messages and requiring a page refresh to recover. To address this problem, React 16 uses a more resilient error-handling strategy. By default, if an error is thrown inside a component's render or lifecycle methods, the whole component tree is unmounted from the root. This prevents the display of corrupted data. However, it's probably not the ideal user experience.
Instead of unmounting the whole app every time there's an error, you can use error boundaries. Error boundaries are special components that capture errors inside their subtree and display a fallback UI in its place. Think of error boundaries like try-catch statements, but for React components.
For more details, check out our [previous post on error handling in React 16](/react/blog/2017/07/26/error-handling-in-react-16.html).
### Portals
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
```js
render() {
// React does *not* create a new div. It renders the children into `domNode`.
// `domNode` is any valid DOM node, regardless of its location in the DOM.
return ReactDOM.createPortal(
this.props.children,
domNode,
);
}
```
See a full example in the [documentation for portals](/react/docs/portals.html).
### Better server-side rendering
React 16 includes a completely rewritten server renderer. It's really fast. It supports **streaming**, so you can start sending bytes to the client faster. And thanks to a [new packaging strategy](#reduced-file-size) that compiles away `process.env` checks (Believe it or not, reading `process.env` in Node is really slow!), you no longer need to bundle React to get good server-rendering performance.
Core team member Sasha Aickin wrote a [great article describing React 16's SSR improvements](https://medium.com/@aickin/whats-new-with-server-side-rendering-in-react-16-9b0d78585d67). According to Sasha's synthetic benchmarks, server rendering in React 16 is roughly **three times faster** than React 15. "When comparing against React 15 with `process.env` compiled out, there’s about a 2.4x improvement in Node 4, about a 3x performance improvement in Node 6, and a full 3.8x improvement in the new Node 8.4 release. And if you compare against React 15 without compilation, React 16 has a full order of magnitude gain in SSR in the latest version of Node!" (As Sasha points out, please be aware that these numbers are based on synthetic benchmarks and may not reflect real-world performance.)
In addition, React 16 is better at hydrating server-rendered HTML once it reaches the client. It no longer requires the initial render to exactly match the result from the server. Instead, it will attempt to reuse as much of the existing DOM as possible. No more checksums! In general, we don't recommend that you render different content on the client versus the server, but it can be useful in some cases (e.g. timestamps).
See the [documentation for `ReactDOMServer`](/react/docs/react-dom-server.html) for more details.
### Support for custom DOM attributes
Instead of ignoring unrecognized HTML and SVG attributes, React will now [pass them through to the DOM](https://facebook.github.io/react/blog/2017/09/08/dom-attributes-in-react-16.html). This has the added benefit of allowing us to get rid of most of React's attribute whitelist, resulting in reduced file sizes.
### Reduced file size
Despite all these additions, React 16 is actually **smaller** compared to 15.6.1!
* `react` is 5.3 kb (2.2 kb gzipped), down from 20.7 kb (6.9 kb gzipped).
* `react-dom` is 103.7 kb (32.6 kb gzipped), down from 141 kb (42.9 kb gzipped).
* `react` + `react-dom` is 109 kb (34.8 kb gzipped), down from 161.7 kb (49.8 kb gzipped).
That amounts to a combined **32% size decrease compared to the previous version (30% post-gzip)**.
The size difference is partly attributable to a change in packaging. React now uses [Rollup](https://rollupjs.org/) to create flat bundles for each of its different target formats, resulting in both size and runtime performance wins. The flat bundle format also means that React's impact on bundle size is roughly consistent regardless of how your ship your app, whether it's with Webpack, Browserify, the pre-built UMD bundles, or any other system.
### MIT licensed
[In case you missed it](https://code.facebook.com/posts/300798627056246/relicensing-react-jest-flow-and-immutable-js/), React 16 is available under the MIT license. We've also published React 15.6.2 under MIT, for those who are unable to upgrade immediately.
### New core architecture
React 16 is the first version of React built on top of a new core architecture, codenamed "Fiber." You can read all about this project over on [Facebook's engineering blog](https://code.facebook.com/posts/1716776591680069/react-16-a-look-inside-an-api-compatible-rewrite-of-our-frontend-ui-library/). (Spoiler: we rewrote React!)
Fiber is responsible for most of the new features in React 16, like error boundaries and fragments. Over the next few releases, you can expect more new features as we begin to unlock the full potential of React.
Perhaps the most exciting area we're working on is **async rendering**—a strategy for cooperatively scheduling rendering work by periodically yielding execution to the browser. The upshot is that, with async rendering, apps are more responsive because React avoids blocking the main thread.
This demo provides an early peek at the types of problems async rendering can solve:
<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Ever wonder what &quot;async rendering&quot; means? Here&#39;s a demo of how to coordinate an async React tree with non-React work <a href="https://t.co/3snoahB3uV">https://t.co/3snoahB3uV</a> <a href="https://t.co/egQ988gBjR">pic.twitter.com/egQ988gBjR</a></p>&mdash; Andrew Clark (@acdlite) <a href="https://twitter.com/acdlite/status/909926793536094209">September 18, 2017</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
*Tip: Pay attention to the spinning black square.*
We think async rendering is a big deal, and represents the future of React. To make migration to v16.0 as smooth as possible, we're not enabling any async features yet, but we're excited to start rolling them out in the coming months. Stay tuned!
## Installation
React v16.0.0 is available on the npm registry.
To install React 16 with Yarn, run:
```bash
yarn add react@^16.0.0 react-dom@^16.0.0
```
To install React 16 with npm, run:
```bash
npm install --save react@^16.0.0 react-dom@^16.0.0
```
We also provide UMD builds of React via a CDN:
```html
<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](/react/docs/installation.html).
## Upgrading
Although React 16 includes significant internal changes, in terms of upgrading, you can think of this like any other major React release. We've been serving React 16 to Facebook and Messenger.com users since earlier this year, and we released several beta and release candidate versions to flush out additional issues. With minor exceptions, **if your app runs in 15.6 without any warnings, it should work in 16.**
### New deprecations
Hydrating a server-rendered container now has an explicit API. If you're reviving server-rendered HTML, use [`ReactDOM.hydrate`](/react/docs/react-dom.html#hydrate) instead of `ReactDOM.render`. Keep using `ReactDOM.render` if you're just doing client-side rendering.
### React Addons
As previously announced, we've [discontinued support for React Addons](/react/blog/2017/04/07/react-v15.5.0.html#discontinuing-support-for-react-addons). We expect the latest version of each addon (except `react-addons-perf`; see below) to work for the foreseeable future, but we won't publish additional updates.
Refer to the previous announcement for [suggestions on how to migrate](/react/blog/2017/04/07/react-v15.5.0.html#discontinuing-support-for-react-addons).
`react-addons-perf` no longer works at all in React 16. It's likely that we'll release a new version of this tool in the future. In the meantime, you can [use your browser's performance tools to profile React components](/react/docs/optimizing-performance.html#profiling-components-with-the-chrome-performance-tab).
### Breaking changes
React 16 includes a number of small breaking changes. These only affect uncommon use cases and we don't expect them to break most apps.
* React 15 had limited, undocumented support for error boundaries using `unstable_handleError`. This method has been renamed to `componentDidCatch`. You can use a codemod to [automatically migrate to the new API](https://github.com/reactjs/react-codemod#error-boundaries).
* `ReactDOM.render` and `ReactDOM.unstable_renderIntoContainer` now return null if called from inside a lifecycle method. To work around this, you can use [portals](https://github.com/facebook/react/issues/10309#issuecomment-318433235) or [refs](https://github.com/facebook/react/issues/10309#issuecomment-318434635).
* `setState`:
* Calling `setState` with null no longer triggers an update. This allows you to decide in an updater function if you want to re-render.
* Calling `setState` directly in render always causes an update. This was not previously the case. Regardless, you should not be calling setState from render.
* `setState` callbacks (second argument) now fire immediately after `componentDidMount` / `componentDidUpdate` instead of after all components have rendered.
* When replacing `<A />` with `<B />`, `B.componentWillMount` now always happens before `A.componentWillUnmount`. Previously, `A.componentWillUnmount` could fire first in some cases.
* Previously, changing the ref to a component would always detach the ref before that component's render is called. Now, we change the ref later, when applying the changes to the DOM.
* It is not safe to re-render into a container that was modified by something other than React. This worked previously in some cases but was never supported. We now emit a warning in this case. Instead you should clean up your component trees using `ReactDOM.unmountComponentAtNode`. [See this example.](https://github.com/facebook/react/issues/10294#issuecomment-318820987)
* `componentDidUpdate` lifecycle no longer receives `prevContext` param. (See [#8631](https://github.com/facebook/react/issues/8631))
* Shallow renderer no longer calls `componentDidUpdate` because DOM refs are not available. This also makes it consistent with `componentDidMount` (which does not get called in previous versions either).
* Shallow renderer does not implement `unstable_batchedUpdates` anymore.
### Packaging
* There is no `react/lib/*` and `react-dom/lib/*` anymore. Even in CommonJS environments, React and ReactDOM are precompiled to single files (“flat bundles”). If you previously relied on undocumented React internals, and they don’t work anymore, let us know about your specific case in a new issue, and we’ll try to figure out a migration strategy for you.
* There is no `react-with-addons.js` build anymore. All compatible addons are published separately on npm, and have single-file browser versions if you need them.
* The deprecations introduced in 15.x have been removed from the core package. `React.createClass` is now available as `create-react-class`, `React.PropTypes` as `prop-types`, `React.DOM` as `react-dom-factories`, `react-addons-test-utils` as `react-dom/test-utils`, and shallow renderer as `react-test-renderer/shallow`. See [15.5.0](https://facebook.github.io/react/blog/2017/04/07/react-v15.5.0.html) and [15.6.0](https://facebook.github.io/react/blog/2017/06/13/react-v15.6.0.html) blog posts for instructions on migrating code and automated codemods.
* The names and paths to the single-file browser builds have changed to emphasize the difference between development and production builds. For example:
* `react/dist/react.js``react/umd/react.development.js`
* `react/dist/react.min.js``react/umd/react.production.min.js`
* `react-dom/dist/react-dom.js``react-dom/umd/react-dom.development.js`
* `react-dom/dist/react-dom.min`.js → `react-dom/umd/react-dom.production.min.js`
## JavaScript Environment Requirements
React 16 depends on the collection types [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). If you support older browsers and devices which may not yet provide these natively (e.g. IE < 11), consider including a global polyfill in your bundled application, such as [core-js](https://github.com/zloirock/core-js) or [babel-polyfill](https://babeljs.io/docs/usage/polyfill/).
A polyfilled environment for React 16 using core-js to support older browsers might look like:
```js
import 'core-js/es6/map';
import 'core-js/es6/set';
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
```
React also depends on `requestAnimationFrame` (even in test environments). A simple shim for test environments would be:
```js
global.requestAnimationFrame = function(callback) {
setTimeout(callback, 0);
};
```
## Acknowledgments
As always, this release would not have been possible without our open source contributors. Thanks to everyone who filed bugs, opened PRs, responded to issues, wrote documentation, and more!
Special thanks to our core contributors, especially for their heroic efforts over the past few weeks during the prerelease cycle: [Brandon Dail](https://twitter.com/aweary), [Jason Quense](https://twitter.com/monasticpanic), [Nathan Hunzaker](https://twitter.com/natehunzaker), and [Sasha Aickin](https://twitter.com/xander76).

12
docs/installation.md

@ -215,21 +215,21 @@ Learn [how to tell if your website is serving the right version of React](/react
### Using a CDN
If you don't want to use npm to manage client packages, the `react` and `react-dom` npm packages also provide single-file distributions in `dist` folders, which are hosted on a CDN:
If you don't want to use npm to manage client packages, the `react` and `react-dom` npm packages also provide single-file distributions in `umd` folders, which are hosted on a CDN:
```html
<script crossorigin src="https://unpkg.com/react@15/dist/react.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
```
The versions above are only meant for development, and are not suitable for production. Minified and optimized production versions of React are available at:
```html
<script crossorigin src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
<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>
```
To load a specific version of `react` and `react-dom`, replace `15` with the version number.
To load a specific version of `react` and `react-dom`, replace `16` with the version number.
If you use Bower, React is available via the `react` package.

90
docs/portals.md

@ -0,0 +1,90 @@
---
id: portals
title: Portals
permalink: docs/portals.html
---
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
```js
ReactDOM.createPortal(child, container)
```
The first argument (`child`) is any [renderable React child](/docs/react-component.html#render), such as an element, string, or fragment. The second argument (`container`) is a DOM element.
## Usage
Normally, when you return an element from a component's render method, it's mounted into the DOM as a child of the nearest parent node:
```js{4,6}
render() {
// React mounts a new div and renders the children into it
return (
<div>
{this.props.children}
</div>
);
}
```
However, sometimes it's useful to insert a child into a different location in the DOM:
```js{6}
render() {
// React does *not* create a new div. It renders the children into `domNode`.
// `domNode` is any valid DOM node, regardless of its location in the DOM.
return React.createPortal(
this.props.children,
domNode,
);
}
```
A typical use case for portals is when a parent component has an `overflow: hidden` or `z-index` style, but you need the child to visually "break out" of its container. For example, dialogs, hovercards, and tooltips.
> Note:
>
> For most uses portals, you'll need to make sure to follow the proper accessibility guidelines.
[Try out an example on CodePen.](https://codepen.io/acdlite/pen/JrKgmz)
## Portals and event bubbling
A nice feature of portals is that, even though the DOM node can be anywhere in the DOM tree, it behaves like a normal React child in every other way. Features like context work exactly the same regardless of whether the child is a portal.
This includes event bubbling: an event fired from inside a portal will propagate to ancestors in the containing *React tree*, even if those elements are not ancestors in the *DOM tree*:
```js
// These two containers are siblings in the DOM
const appContainer = document.getElementById('app-container');
const modalContainer = document.getElementById('modal-container');
class Parent extends React.Component {
state = {clicks: 0};
onClick = () => {
// This will fire when the button in Child is clicked, even though
// button is not direct descendant in the DOM.
this.setState(state => ({clicks: state.clicks + 1}));
};
render() {
return (
<div onClick={this.onClick}>
<p>Number of clicks: {this.state.clicks}</p>
<p>Open up the browser DevTools to observe that the button is not a child the div with onClick handler.</p>
{ReactDOM.createPortal(<Child />, modalContainer)}
</div>
);
}
}
function Child() {
return <button>Click</button>;
}
ReactDOM.render(<Parent />, appContainer);
```
[Try this example on CodePen](https://codepen.io/acdlite/pen/MEJEVV).
The advantage of treating portal event bubbling this way is that it makes it easier to build abstractions. For example, if you render a `<Modal />` component, the parent can capture its events regardless of whether it's implemented using portals.

32
docs/reference-javascript-environment-requirements.md

@ -0,0 +1,32 @@
---
id: javascript-environment-requirements
title: JavaScript Environment Requirements
layout: docs
category: Reference
permalink: docs/javascript-environment-requirements.html
---
React 16 depends on the collection types [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). If you support older browsers and devices which may not yet provide these natively (e.g. IE < 11), consider including a global polyfill in your bundled application, such as [core-js](https://github.com/zloirock/core-js) or [babel-polyfill](https://babeljs.io/docs/usage/polyfill/).
A polyfilled environment for React 16 using core-js to support older browsers might look like:
```js
import 'core-js/es6/map';
import 'core-js/es6/set';
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
```
React also depends on `requestAnimationFrame` (even in test environments). A simple shim for testing environments would be:
```js
global.requestAnimationFrame = function(callback) {
setTimeout(callback, 0);
};
```

28
docs/reference-react-component.md

@ -91,9 +91,15 @@ render()
The `render()` method is required.
When called, it should examine `this.props` and `this.state` and return a single React element. This element can be either a representation of a native DOM component, such as `<div />`, or another composite component that you've defined yourself.
When called, it should examine `this.props` and `this.state` and return one of the following types:
You can also return `null` or `false` to indicate that you don't want anything rendered. When returning `null` or `false`, `ReactDOM.findDOMNode(this)` will return `null`.
- **React elements.** Typically created via JSX. A element can either be a representation of a native DOM component (`<div />`), or a user-defined composite component (`<MyComponent />`).
- **String and numbers.** These are rendered as text nodes in the DOM.
- **Portals**. Created with [`ReactDOM.createPortal`](/react/docs/portals.html).
- `null`. Renders nothing.
- **Booleans**. Render nothing. (Mostly exists to support `return test && <Child />` pattern, where `test` is boolean.)
When returning `null` or `false`, `ReactDOM.findDOMNode(this)` will return `null`.
The `render()` function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes components easier to think about.
@ -101,6 +107,24 @@ The `render()` function should be pure, meaning that it does not modify componen
>
> `render()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false.
#### Fragments
You can also return multiple items from `render()` using an array:
```javascript
render() {
return [
<li key="A"/>First item</li>,
<li key="B"/>Second item</li>,
<li key="C"/>Third item</li>,
];
}
```
> Note:
>
> Don't forget to [add keys](https://facebook.github.io/react/docs/lists-and-keys.html#keys) to elements in a fragment to avoid the key warning.
* * *
### `constructor()`

46
docs/reference-react-dom-node-stream.md

@ -1,46 +0,0 @@
---
id: react-dom-node-stream
title: ReactDOMNodeStream
layout: docs
category: Reference
permalink: docs/react-dom-node-stream.html
---
If you use ES6 with npm, you can write `import ReactDOMNodeStream from 'react-dom/node-stream'`. If you use ES5 with npm, you can write `var ReactDOMNodeStream = require('react-dom/node-stream')`.
Unlike other packages in React, `ReactDOMNodeStream` depends on a package (`stream`) that is available in Node.js but not in the browser. For this reason, there is no `<script>` tag version of `ReactDOMNodeStream`; it is only provided as a Node.js module.
## Overview
The `ReactDOMNodeStream` object allows you to render your components in Node.js and stream the resulting markup.
- [`renderToNodeStream()`](#rendertonodestream)
- [`renderToStaticNodeStream()`](#rendertostaticnodestream)
* * *
## Reference
### `renderToNodeStream()`
```javascript
ReactDOMNodeStream.renderToNodeStream(element)
```
Render a React element to its initial HTML. This should only be used in Node.js; it will not work in the browser, since the browser does not support Node.js streams. React will return a [Readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) that outputs an HTML string. The HTML output by this stream will be exactly equal to what [`ReactDOMServer.renderToString`](https://facebook.github.io/react/docs/react-dom-server.html#rendertostring) would return. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call [`ReactDOM.render()`](/react/docs/react-dom.html#render) on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
Note that the stream returned from this method will return a byte stream encoded in utf-8. If you need a stream in another encoding, take a look a project like [iconv-lite](https://www.npmjs.com/package/iconv-lite), which provides transform streams for transcoding text.
* * *
### `renderToStaticNodeStream()`
```javascript
ReactDOMNodeStream.renderToStaticNodeStream(element)
```
Similar to [`renderToNodeStream`](#rendertonodestream), except this doesn't create extra DOM attributes such as `data-reactid`, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.
Note that the stream returned from this method will return a byte stream encoded in utf-8. If you need a stream in another encoding, take a look a project like [iconv-lite](https://www.npmjs.com/package/iconv-lite), which provides transform streams for transcoding text.

72
docs/reference-react-dom-server.md

@ -6,14 +6,42 @@ category: Reference
permalink: docs/react-dom-server.html
---
If you load React from a `<script>` tag, these top-level APIs are available on the `ReactDOMServer` global. If you use ES6 with npm, you can write `import ReactDOMServer from 'react-dom/server'`. If you use ES5 with npm, you can write `var ReactDOMServer = require('react-dom/server')`.
The `ReactDOMServer` object enables you to render components to static markup. Typically, it's used on a Node server:
```js
// ES modules
import ReactDOMServer from 'react-dom/server';
// CommonJS
var ReactDOMServer = require('react-dom/server');
```
We also provide a separate entry-point for use in the browser:
```js
// ES modules
import ReactDOMServer from 'react-dom/server.browser';
// CommonJS
var ReactDOMServer = require('react-dom/server.browser');
```
Or, using UMD:
```html
<script crossorigin src="https://unpkg.com/react-dom/umd/react-dom-server.browser.production.min.js" />
<!-- Accessible as window.ReactDOMServer -->
```
## Overview
The `ReactDOMServer` object allows you to render your components on the server.
The following methods can be used in both the server and browser environments:
- [`renderToString()`](#rendertostring)
- [`renderToStaticMarkup()`](#rendertostaticmarkup)
These additional methods depend on a package (`stream`) that is **only available on the server**, and won't work in the browser.
- [`renderToString()`](#rendertostring)
- [`renderToStaticMarkup()`](#rendertostaticmarkup)
- [`renderToNodeStream()`](#rendertonodestream)
- [`renderToStaticNodeStream()`](#rendertostaticnodestream)
* * *
@ -25,9 +53,9 @@ The `ReactDOMServer` object allows you to render your components on the server.
ReactDOMServer.renderToString(element)
```
Render a React element to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
Render a React element to its initial HTML. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call [`ReactDOM.render()`](/react/docs/react-dom.html#render) on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
If you call [`ReactDOM.hydrate()`](/react/docs/react-dom.html#hydrate) on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
* * *
@ -38,3 +66,35 @@ ReactDOMServer.renderToStaticMarkup(element)
```
Similar to [`renderToString`](#rendertostring), except this doesn't create extra DOM attributes such as `data-reactid`, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.
* * *
### `renderToNodeStream()`
```javascript
ReactDOMNodeStream.renderToNodeStream(element)
```
Render a React element to its initial HTML. Returns a [Readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) that outputs an HTML string. The HTML output by this stream is exactly equal to what [`ReactDOMServer.renderToString`](#rendertostring) would return.
> Note:
>
> Server-only. This API is not available in the browser.
>
> The stream returned from this method will return a byte stream encoded in utf-8. If you need a stream in another encoding, take a look a project like [iconv-lite](https://www.npmjs.com/package/iconv-lite), which provides transform streams for transcoding text.
* * *
### `renderToStaticNodeStream()`
```javascript
ReactDOMNodeStream.renderToStaticNodeStream(element)
```
Similar to [`renderToNodeStream`](#rendertonodestream), except this doesn't create extra DOM attributes such as `data-reactid`, that React uses internally. The HTML output by this stream is exactly equal to what [`ReactDOMServer.renderToStaticMarkup`](#rendertostaticmarkup) would return.
> Note:
>
> Server-only. This API is not available in the browser.
>
> The stream returned from this method will return a byte stream encoded in utf-8. If you need a stream in another encoding, take a look a project like [iconv-lite](https://www.npmjs.com/package/iconv-lite), which provides transform streams for transcoding text.

28
docs/reference-react-dom.md

@ -13,8 +13,10 @@ If you load React from a `<script>` tag, these top-level APIs are available on t
The `react-dom` package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside of the React model if you need to. Most of your components should not need to use this module.
- [`render()`](#render)
- [`hydrate()`](#hydrate)
- [`unmountComponentAtNode()`](#unmountcomponentatnode)
- [`findDOMNode()`](#finddomnode)
- [`createPortal()`](#createPortal)
### Browser Support
@ -53,6 +55,22 @@ If the optional callback is provided, it will be executed after the component is
> `ReactDOM.render()` currently returns a reference to the root `ReactComponent` instance. However, using this return value is legacy
> and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root `ReactComponent` instance, the preferred solution is to attach a
> [callback ref](/react/docs/more-about-refs.html#the-ref-callback-attribute) to the root element.
>
> Using `ReactDOM.render()` to hydrate a server-rendered container is deprecated and will be removed in React 17. Use [`hydrate()`](#hydrate) instead.
* * *
### `hydrate()`
```javascript
ReactDOM.hydrate(
element,
container,
[callback]
)
```
Same as [`render()`](#render), but is used to hydrate a container whose HTML contents were rendered by [`ReactDOMServer`](/react/docs/react-dom-server.html). React will attach event listeners while preserving as much of the existing DOM as possible. For best results, you should try to render the same content on the server as on the client, with as few differences as possible.
* * *
@ -80,3 +98,13 @@ If this component has been mounted into the DOM, this returns the corresponding
> `findDOMNode` only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling `findDOMNode()` in `render()` on a component that has yet to be created) an exception will be thrown.
>
> `findDOMNode` cannot be used on functional components.
* * *
### `createPortal()`
```javascript
ReactDOM.createPortal(child, container)
```
Creates a portal. Portals provide a way to [render children into a DOM node that exists outside the hierarchy of the DOM component](/react/docs/portals.html).
Loading…
Cancel
Save