You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

194 lines
7.5 KiB

---
id: react-api
title: React Top-Level API
layout: docs
category: Reference
permalink: docs/react-api.html
8 years ago
redirect_from:
- "docs/reference.html"
- "docs/clone-with-props.html"
- "docs/top-level-api.html"
- "docs/top-level-api-ja-JP.html"
- "docs/top-level-api-ko-KR.html"
- "docs/top-level-api-zh-CN.html"
8 years ago
- "docs/glossary.html"
---
`React` is the entry point to the React library. If you load React from a `<script>` tag, these top-level APIs are available on the `React` global. If you use ES6 with npm, you can write `import React from 'react'`. If you use ES5 with npm, you can write `var React = require('react')`.
## Overview
### Components
React components let you split the UI into independent, reusable pieces, and think about each piece in isolation. React components can be defined by subclassing `React.Component` or `React.PureComponent`.
- [`React.Component`](#react.component)
- [`React.PureComponent`](#react.purecomponent)
All doc updates forv15.5 (#9359) * `react-addons-test-utils` -&gt; `react-dom/test-utils` Updating all references and docs on the `React.addons.TestUtils` and the shallow renderer to refer to the correct targets. Instead of: ``` const React = require(&#39;react&#39;); // ... React.addons.Testutils // or const ReactTestUtils = require(&#39;react-addons-test-utils&#39;); ``` we now show: ``` const ReactTestUtils = require(&#39;react-dom/test-utils&#39;); ``` And for shallow renderer, instead of: ``` const shallowRenderer = TestUtils.createRenderer(); ``` we now show: ``` const shallowRenderer = require(&#39;react-test-renderer/shallow&#39;); ``` * Update the &#39;prev&#39; and &#39;next&#39; attributes of &#39;add-ons&#39; docs These flags are used to set arrow links to easily navigate through the documents. They were wrong or missing in some of the &#39;add-ons&#39; pages and this bothered me when manually testing the updates from the previous commit. * Update syntax for instantiating shallow renderer Missed this when updating the docs for the changes to shallow-renderer in React 15.5. * Fix pointers in addons docs Thanks @bvaughn for catching this * Make example of shallow renderer more consistent We should show using the same variable names between code samples. * Make names in example even more consistent We should use the same variable name for the same thing across examples. `renderer` -&gt; `shallowRenderer`. * Update docs to deprecate React&lt;CSS&gt;TransitionGroup - removes link to the docs about `ReactCSSTransitionGroup` and `ReactTransitionGroup` from the main navigation - updates &#39;prev&#39; and &#39;next&#39; pointers to skip this page - adds deprecation warning to the top of the page - remove references to these modules from the packages README - updates &#39;add-ons&#39; main page to list this as a deprecated add-on * Update `React.createClass` to `createReactClass` in the docs The `React.createClass` method is being deprecated in favor of `createReactClass`. * Remove &#39;React.createClass&#39; from top level API docs It no longer makes sense to have a section for the &#39;createClass&#39; method in this page, since it won&#39;t be available as a top level method on &#39;React&#39;. I initially was going to pull the section about &#39;createClass&#39; into a separate page to add under &#39;addons&#39; but it was short and duplicative of the &#39;react-without-es6&#39; docs. So I just linked to those. * Remove *most* `React.PropTypes` from the docs I am doing the docs for `context` in a separate commit because that case was a bit less clear-cut. We will no longer support `React.PropTypes` as a built-in feature of React, and instead should direct folks to use the `PropTypes` project that stands alone. Rather than retaining the `React.PropTypes` examples and just revamping them to show the use of the stand-alone `PropTypes` library with React, it makes more sense to direct people to that project and reduce the perceived API area and complexity of React core. The proper place to document `PropTypes` is in the README or docs of that project, not in React docs. * Update `context` docs to not use `React.PropTypes` We use `React.PropTypes` to define the `contextType` for the `context` feature of React. It&#39;s unclear how this will work once `React.PropTypes` is replaced by the external `PropTypes` library. Some options; a) Deprecate `context`, either in v16 or shortly after. Seems reasonable based on the intense warnings against using context that we have in the docs - https://facebook.github.io/react/docs/context.html#why-not-to-use-context **Except** that probably some widely used libraries depend on it, like `React-Router`. b) Expect users will use external `PropTypes` library when defining `contextTypes` and just don&#39;t do our `checkReactTypeSpec` against them any more in v16. c) Stop masking context and pass the whole context unmasked everywhere. Worst option, do not recommend. I went with `b` and assume that, for now, we will get users to use the external `PropTypes` when defining context. I will update this PR if we want a different approach. * Remove &#39;addons&#39; items from left nav, and deprecate &#39;addons&#39; doc page The plan: [X] Remove links to &#39;addons&#39; items from main navigation [X] Add deprecation notices where appropriate, and update syntax to show using the separate modules. [ ] Update other references to &#39;React.addons&#39; in docs. Coming in next commit. --- blocked but coming in future PRs [ ] Link to a blog post describing the new locations of add-ons in the deprecation notice on the &#39;/docs/addons.html&#39; page. Blocked until we actually publish that blog post. [ ] Move the docs for each add-on to the actual github repo where it now lives. [ ] Redirect the old add-ons doc permalinks to the docs in the separate github repos for those modules. [ ] Remove the old add-ons doc markdown files from React core docs. * Remove references to `React.addons` from docs Just misc. places where we referenced the &#39;addons&#39; feature. All gone!
8 years ago
If you don't use ES6 classes, you may use the `create-react-class` module instead. See [Using React without ES6](/react/docs/react-without-es6.html) for more information.
### Creating React Elements
We recommend [using JSX](/react/docs/introducing-jsx.html) to describe what your UI should look like. Each JSX element is just syntactic sugar for calling [`React.createElement()`](#createelement). You will not typically invoke the following methods directly if you are using JSX.
- [`createElement()`](#createelement)
- [`createFactory()`](#createfactory)
See [Using React without JSX](/react/docs/react-without-jsx.html) for more information.
### Transforming Elements
`React` also provides some other APIs:
- [`cloneElement()`](#cloneelement)
- [`isValidElement()`](#isvalidelement)
- [`React.Children`](#react.children)
* * *
## Reference
### `React.Component`
`React.Component` is the base class for React components when they are defined using [ES6 classes](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes).
```javascript
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
```
See the [React.Component API Reference](/react/docs/react-component.html) for a list of methods and properties related to the base `React.Component` class.
* * *
### `React.PureComponent`
`React.PureComponent` is exactly like [`React.Component`](#react.component) but implements [`shouldComponentUpdate()`](/react/docs/react-component.html#shouldcomponentupdate) with a shallow prop and state comparison.
If your React component's `render()` function renders the same result given the same props and state, you can use `React.PureComponent` for a performance boost in some cases.
> Note
> `React.PureComponent`'s `shouldComponentUpdate()` only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extend `PureComponent` when you expect to have simple props and state, or use [`forceUpdate()`](/react/docs/react-component.html#forceupdate) when you know deep data structures have changed. Or, consider using [immutable objects](https://facebook.github.io/immutable-js/) to facilitate fast comparisons of nested data.
>
> Furthermore, `React.PureComponent`'s `shouldComponentUpdate()` skips prop updates for the whole component subtree. Make sure all the children components are also "pure".
* * *
### `createElement()`
```javascript
React.createElement(
type,
[props],
[...children]
)
```
Create and return a new [React element](/react/docs/rendering-elements.html) of the given type. The type argument can be either a tag name string (such as `'div'` or `'span'`), or a [React component](/react/docs/components-and-props.html) type (a class or a function).
Convenience wrappers around `React.createElement()` for DOM components are provided by `React.DOM`. For example, `React.DOM.a(...)` is a convenience wrapper for `React.createElement('a', ...)`. They are considered legacy, and we encourage you to either use JSX or use `React.createElement()` directly instead.
Code written with [JSX](/react/docs/introducing-jsx.html) will be converted to use `React.createElement()`. You will not typically invoke `React.createElement()` directly if you are using JSX. See [React Without JSX](/react/docs/react-without-jsx.html) to learn more.
* * *
### `cloneElement()`
```
React.cloneElement(
element,
[props],
[...children]
)
```
Clone and return a new React element using `element` as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. `key` and `ref` from the original element will be preserved.
`React.cloneElement()` is almost equivalent to:
```js
<element.type {...element.props} {...props}>{children}</element.type>
```
However, it also preserves `ref`s. This means that if you get a child with a `ref` on it, you won't accidentally steal it from your ancestor. You will get the same `ref` attached to your new element.
This API was introduced as a replacement of the deprecated `React.addons.cloneWithProps()`.
* * *
### `createFactory()`
```javascript
React.createFactory(type)
```
Return a function that produces React elements of a given type. Like [`React.createElement()`](#createElement), the type argument can be either a tag name string (such as `'div'` or `'span'`), or a [React component](/react/docs/components-and-props.html) type (a class or a function).
This helper is considered legacy, and we encourage you to either use JSX or use `React.createElement()` directly instead.
You will not typically invoke `React.createFactory()` directly if you are using JSX. See [React Without JSX](/react/docs/react-without-jsx.html) to learn more.
* * *
### `isValidElement()`
```javascript
React.isValidElement(object)
```
Verifies the object is a React element. Returns `true` or `false`.
* * *
### `React.Children`
`React.Children` provides utilities for dealing with the `this.props.children` opaque data structure.
#### `React.Children.map`
```javascript
React.Children.map(children, function[(thisArg)])
```
Invokes a function on every immediate child contained within `children` with `this` set to `thisArg`. If `children` is a keyed fragment or array it will be traversed: the function will never be passed the container objects. If children is `null` or `undefined`, returns `null` or `undefined` rather than an array.
#### `React.Children.forEach`
```javascript
React.Children.forEach(children, function[(thisArg)])
```
Like [`React.Children.map()`](#react.children.map) but does not return an array.
#### `React.Children.count`
```javascript
React.Children.count(children)
```
Returns the total number of components in `children`, equal to the number of times that a callback passed to `map` or `forEach` would be invoked.
#### `React.Children.only`
```javascript
React.Children.only(children)
```
Returns the only child in `children`. Throws otherwise.
#### `React.Children.toArray`
```javascript
React.Children.toArray(children)
```
Returns the `children` opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice `this.props.children` before passing it down.
> Note:
>
> `React.Children.toArray()` changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, `toArray` prefixes each key in the returned array so that each element's key is scoped to the input array containing it.