<li><ahref="/react/docs/03-interactivity-and-dynamic-uis.html"{%ifpage.id =='03-interactivity-and-dynamic-uis'%}class="active"{%endif%}>Interactivity and dynamic UIs</a></li>
<li><ahref="/react/docs/03-interactivity-and-dynamic-uis.html"{%ifpage.id =='03-interactivity-and-dynamic-uis'%}class="active"{%endif%}>Interactivity and Dynamic UIs</a></li>
<li><ahref="/react/docs/07-working-with-the-browser.html"{%ifpage.id =='07-working-with-the-browser'%}class="active"{%endif%}>Working with the browser</a></li>
<li><ahref="/react/docs/07-working-with-the-browser.html"{%ifpage.id =='07-working-with-the-browser'%}class="active"{%endif%}>Working With the Browser</a></li>
@ -8,20 +8,20 @@ React is a JavaScript library for creating user interfaces by Facebook and Insta
We built React to solve one problem: **building large applications with data that changes over time**. To do this, React has two main ideas.
### Stay simple and declarative
### Stay Simple and Declarative
React apps are easy to write. Simply express how the UI should look at any given point in time, and React will manage all UI updates for you when your underlying data changes.
It's just like writing a server-rendered web app: when the data changes, React conceptually hits the refresh button, except React is very fast and maintains the state of your UI. Because of this, React's API is very small and easy to understand.
### Build composable components
## Build Composable Components
React is all about building reusable components. In fact, with React the *only* thing you do is build components. Since they're so encapsulated, components make code reuse, testing, and separation of concerns easy.
### Give it five minutes
## Give it Five Minutes
React challenges a lot of conventional wisdom, and at first glance some of the ideas may seem crazy. We ask that you [give it five minutes](http://37signals.com/svn/posts/3124-give-it-five-minutes) while reading about React; engineers and designers have built thousands of components both inside and outside of Facebook and Instagram, and we hope you'll find it useful!
### Learn more
## Learn More
You can learn more about our motivations behind building React in [this blog post](http://facebook.github.io/react/blog/2013/06/05/why-react.html).
The most basic thing you can do with a UI is display some data. React makes it easy to display data, and automatically keeps it up-to-date when the data changes.
### Getting started
## Getting Started
Let's look at a really simple example. Create a `hello-react.html` file with the following code:
@ -54,7 +54,7 @@ setInterval(function() {
}, 500);
```
### Reactive updates
## Reactive Updates
View the finished code in a web browser and type your name into the text field. Notice that React is only changing the time string in the UI -- any input you put in the text field remains, even though you haven't written any code to manage this behavior. React figures it out for you and does the right thing.
@ -62,13 +62,13 @@ The way it is able to figure this out is that React does not directly manipulate
The inputs to this component are called `props` -- short for "properties". They're passed as attributes in JSX syntax. You should think of these as immutable within the component, that is, **never write to this.props**.
### Components are just like functions
## Components are Just Like Functions
React components are very simple. You can think of them as simple function that take in `props` and `state` (discussed later) and render HTML. Because they're so simple, it makes them very easy to reason about.
**One limitation**: React components can only render a single root node. If you want to return multiple nodes they *must* be wrapped in a single root. This is a limitation we can fix, but we have not identified a pressing reason to do so yet; reach out to our [Google Group](http://groups.google.com/group/reactjs) if you have a compelling case for it.
### JSX syntax
## JSX Syntax
We strongly believe that components are the right way to separate concerns rather than "templates" and "display logic." We think that markup and the code that generates it are intimately tied together. Additionally, display logic is often very complex and using template languages to express it becomes cumbersome.
JSX looks like HTML but there are some important differences you may run into.
### Whitespace removal
## Whitespace removal
JSX doesn't follow the same whitespace elimination rules as HTML. JSX removes all whitespace between two curly braces expressions. If you want to have whitespace, simply add `{' '}`.
@ -17,7 +17,7 @@ JSX doesn't follow the same whitespace elimination rules as HTML. JSX removes al
Follow [Issue #65](https://github.com/facebook/react/issues/65) for discussion on this behavior.
### HTML Entities
## HTML Entities
You can insert HTML entities within literal text in JSX:
@ -57,7 +57,7 @@ As a last resort, you always have the ability to insert raw HTML.
If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with `data-`.
You've already [learned how to display data](./02-displaying-data.html) with React. Now let's look at how to make our UIs interactive.
### A simple example
## A Simple Example
```javascript
/** @jsx React.DOM */
@ -35,13 +35,13 @@ React.renderComponent(
);
```
### Event handling and synthetic events
## Event Handling and Synthetic Events
With React you simply pass your event handler as a camelCased prop similar to how you'd do it in normal HTML. React ensures that all events behave identically in IE8 and above by implementing a synthetic event system. That is, React knows how to bubble and capture events according to the spec, and the events passed to your event handler are guaranteed to be consistent with [the W3C spec](http://www.w3.org/TR/DOM-Level-3-Events/), regardless of which browser you're using.
**If you'd like to use React on a touch device** (i.e. a phone or tablet), simply call `React.initializeTouchEvents(true);` to turn them on.
### Under the hood: autoBind and event delegation
## Under the Hood: autoBind and Event Delegation
Under the hood React does a few things to keep your code performant and easy to understand.
@ -49,17 +49,17 @@ Under the hood React does a few things to keep your code performant and easy to
**Event delegation.** React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from a fast internal event mapping. When the event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops. To learn more about why this is fast, see [David Walsh's excellent blog post](http://davidwalsh.name/event-delegate).
### Components are just state machines
## Components are Just State Machines
React thinks of UIs as simple state machines. By thinking of a UI as being in various states and rendering those states, it's easy to keep your UI consistent.
In React, you simply update a component's state, and then render a new UI based on this new state. React takes care of updating the DOM for you in the most efficient way.
### How state works
## How State Works
A common way to inform React of a data change is by calling `setState(data, callback)`. This method merges `data` into `this.state` and re-renders the component. When the component finishes re-rendering, the optional `callback` is called. Most of the time you'll never need to provide a `callback` since React will take care of keeping your UI up-to-date for you.
### What components should have state?
## What Components Should Have State?
Most of your components should simply take some data from `props` and render it. However, sometimes you need to respond to user input, a server request or the passage of time. For this you use state.
@ -67,11 +67,11 @@ Most of your components should simply take some data from `props` and render it.
A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via `props`. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way.
### What should go in state?
## What Should Go in State?
**State should contain data that the component's event handlers may change to trigger a UI update.** In real apps this data tends to be very small and JSON-serializable. When building a stateful component, think about the minimal possible representation of its state, and only store those properties in `this.state`. Inside of `render()` simply compute any other information you need based on this state. You'll find that thinking about and writing applications in this way tends to lead to the most correct application, since adding redundant or computed values to state means that you need to explicitly keep them in sync rather than rely on React computing them for you.
### What *shouldn't* go in state?
## What *Shouldn't* Go in State?
`this.state` should only contain the minimal amount of data needed to represent your UI's state. As such, it should not contain:
So far, we've looked at how to write a single component to display data and handle user input. Next let's examine one of React's finest features: composability.
### Motivation: separation of concerns
## Motivation: Separation of Concerns
By building modular components that reuse other components with well-defined interfaces, you get much of the same benefits that you get by using functions or classes. Specifically you can *separate the different concerns* of your app however you please simply by building new components. By building a custom component library for your application, you are expressing your UI in a way that best fits your domain.
### Composition example
## Composition Example
Let's create a simple Avatar component which shows a profile picture and username using the Facebook Graph API.
@ -53,13 +53,13 @@ React.renderComponent(
);
```
### Ownership
## Ownership
In the above example, instances of `Avatar`*own* instances of `ProfilePic` and `ProfileLink`. In React, **an owner is the component that sets the `props` of other components**. More formally, if a component `X` is created in component `Y`'s `render()` method, it is said that `X` is *owned by*`Y`. As discussed earlier, a component cannot mutate its `props` -- they are always consistent with what its owner sets them to. This key property leads to UIs that are guaranteed to be consistent.
It's important to draw a distinciton between the owner-ownee relationship and the parent-child relationship. The owner-ownee relationship is specific to React, while the parent-child relationship is simply the one you know and love from the DOM. In the example above, `Avatar` owns the `div`, `ProfilePic` and `ProfileLink` instances, and `div` is the **parent** (but not owner) of the `ProfilePic` and `ProfileLink` instances.
### Children
## Children
When you create a React component instance, you can include additional React components or JavaScript expressions between the opening and closing tags like this:
@ -69,7 +69,7 @@ When you create a React component instance, you can include additional React com
`Parent` can read its children by accessing the special `this.props.children` prop.
#### Child Reconciliation
### Child Reconciliation
> Reconciliation is the process by which React updates the DOM with each new render pass.
@ -84,7 +84,7 @@ In general, children are reconciled according to the order in which they are ren
Intuitively, `<p>Paragraph 1</p>` was removed. Instead, React will reconcile the DOM by changing the text content of the first child and destroying the last child. React reconciles according to the *order* of the children.
#### Stateful Children
### Stateful Children
For most components, this is not a big deal. However, for stateful components that maintain data in `this.state` across render passes, this can be very problematic.
@ -97,7 +97,7 @@ In most cases, this can be sidestepped by hiding elements instead of destroying
The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a `key`:
@ -116,11 +116,11 @@ The situation gets more complicated when the children are shuffled around (as in
When React reconciles the keyed children, it will ensure that any child with `key` will be reordered (instead of clobbered) or destroyed (instead of reused).
### Data flow
## Data flow
In React, data flows from owner to owned component through `props` as discussed above. This is effectively one-way data binding: owners bind their owned component's props to some value the owner has computed based on its `props` or `state`. Since this process happens recursively, data changes are automatically reflected everywhere they are used.
### A note on performance
## A Note on Performance
You may be thinking that it's expensive to react to changing data if there are a large number of nodes under an owner. The good news is that JavaScript is fast and `render()` methods tend to be quite simple, so in most applications this is extremely fast. Additionally, the bottleneck is almost always the DOM mutation and not JS execution, and React will optimize this for you using batching and change detection.
When designing interfaces, break down the common design elements (buttons, form fields, layout components, etc) into reusable components with well-defined interfaces. That way, the next time you need to build some UI you can write much less code, which means faster development time, less bugs, and less bytes down the wire.
### Prop validation
## Prop Validation
As your app grows it's helpful to ensure that your components are used correctly. We do this using `propTypes`.
** TODO zpao **
### Transferring props: a shortcut
## Transferring Props: A Shortcut
A common type of React component is one that extends a basic HTML in a simple way. Often you'll want to copy any HTML attributes passed to your component to the underlying HTML element to save typing. React provides `transferPropsTo()` to do just this.
@ -36,7 +36,7 @@ React.renderComponent(
);
```
### Mixins
## Mixins
Components are the best way to reuse code in React, but sometimes very different components may share some common functionality. These are sometimes called [cross-cutting concerns](http://en.wikipedia.org/wiki/Cross-cutting_concern). React provides `mixins` to solve this problem.
@ -85,6 +85,6 @@ React.renderComponent(
A nice feature of mixins is that if a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called.
Form components such as `<input>`, `<textarea>`, and `<option>` differ from other native components because they can be mutated via user interactions. These components provide interfaces that make it easier to manage forms in response to user interactions.
### Interactive Props
## Interactive Props
Form components support a few props that are affected via user interactions:
@ -25,7 +25,7 @@ Form components allow listening for changes by setting a callback to the `onChan
Like all DOM events, the `onChange` prop is supported on all native components and can be used to listen to bubbled change events.
### Controlled Components
## Controlled Components
An `<input>` with `value` set is a *controlled* component. In a controlled `<input>`, the value of the rendered element will always reflect the `value` prop. For example:
@ -60,7 +60,7 @@ In this example, we are simply accepting the newest value provided by the user a
This would accept user input but truncate the value to the first 140 characters.
### Uncontrolled Components
## Uncontrolled Components
An `<input>` that does not supply a `value` (or sets it to `null`) is an *uncontrolled* component. In an uncontrolled `<input>`, the value of the rendered element will reflect the user's input. For example:
@ -84,9 +84,9 @@ This example will function much like the **Controlled Components** example above
Likewise, `<input>` supports `defaultChecked` and `<option>` supports `defaultSelected`.
### Advanced Topics
## Advanced Topics
#### Why controlled components?
### Why Controlled Components?
Using form components such as `<input>` in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:
@ -106,7 +106,7 @@ Unlike HTML, React components must represent the state of the view at any point
Since this method describes the view at any point in time, the value of the text input should *always* be `Untitled`.
#### Why textarea value?
### Why Textarea Value?
In HTML, the value of `<textarea>` is usually set using its children:
React provides powerful abstractions that free you from touching the DOM directly in most cases, but sometimes you simply need to access the underlying API, perhaps to work with a third-party library or existing code.
### The mock DOM
## The Mock DOM
React is so fast because it never talks to the DOM directly. React maintains a fast in-memory representation of the DOM. `render()` methods return a *description* of the DOM, and React can diff this description with the in-memory representation to compute the fastest way to update the browser.
@ -15,7 +15,7 @@ Additionally, React implements a full synthetic event system such that all event
Most of the time you should stay within React's "faked browser" world since it's more performant and easier to reason about. However, sometimes you simply need to access the underlying API, perhaps to work with a third-party library like a jQuery plugin. React provides escape hatches for you to use the underlying DOM API directly.
### Refs and getDOMNode()
## Refs and getDOMNode()
To interact with the browser, you'll need a reference to a DOM node. Every mounted React component has a `getDOMNode()` function which you can call to get a reference to it.
@ -53,11 +53,11 @@ React.renderComponent(
);
```
### More about refs
## More About Refs
To learn more about refs, including ways to use them effectively, see our [more about refs](./07.1-more-about-refs.html) documentation.
### Component lifecycle
## Component Lifecycle
Components have three main parts of their lifecycle:
- **Mounting:** A component is being inserted into the DOM.
@ -66,24 +66,24 @@ Components have three main parts of their lifecycle:
React provides lifecycle methods that you can override to hook into this process. We provide **will** methods, which are called right before something happens, and **did** methods which are called right after something happens.
#### Mounting
### Mounting
- `getInitialState(): object` is invoked before a component is mounted. Stateful components should implement this and return the initial state data.
- `componentWillMount()` is invoked immediately before mounting occurs.
- `componentDidMount(DOMElement rootNode)` is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here.
#### Updating
### Updating
- `componentWillReceiveProps(object nextProps)` is invoked when a mounted component receives new props. This method should be used to compare `this.props` and `nextProps` to perform state transitions using `this.setState()`.
- `shouldComponentUpdate(object nextProps, object nextState): boolean` is invoked when a component decides whether any changes warrant an update to the DOM. Implement this as an optimization to compare `this.props` with `nextProps` and `this.state` with `nextState` and return false if React should skip updating.
- `componentWillUpdate(object nextProps, object nextState)` is invoked immediately before updating occurs. You cannot call `this.setState()` here.
- `componentDidUpdate(object prevProps, object prevState, DOMElement rootNode)` is invoked immediately after updating occurs.
#### Unmounting
### Unmounting
- `componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Cleanup should go here.
#### Mounted Methods
### Mounted Methods
_Mounted_ composite components also support the following methods:
@ -96,14 +96,14 @@ _Mounted_ composite components also support the following methods:
> `componentDidUpdate()` is a convenience. The same node can be obtained by
> calling `this.getDOMNode()`.
### Browser suppport and polyfills
## Browser Suppport and Polyfills
At Facebook, we support older browsers, including IE8. We've had polyfills in place for a long time to allow us to write forward-thinking JS. This means we don't have a bunch of hacks scattered throughout our codebase and we can still expect our code to "just work". For example, instead of seeing `+new Date()`, we can just write `Date.now()`. Since the open source React is the same as what we use internally, we've carried over this philosophy of using forward thinking JS.
In addition to that philosphy, we've also taken the stance that we, as authors of a JS library, should not be shipping polyfills as a part of our library. If every library did this, there's a good chance you'd be sending down the same polyfill multiple times, which could be a sizable chunk of dead code. If your product needs to support older browsers, chances are you're already using something like [es5-shim](https://github.com/kriskowal/es5-shim).
@ -63,7 +63,7 @@ In this counterexample, the `<input />` is merely a *description* of an `<input
So how do we talk to the *real* backing instance of the input?
### The `ref` attribute
## The `ref` Attribute
React supports a very special property that you can attach to any component that is output from `render()`. This special property allows you to refer to the corresponding **backing instance** of anything returned from `render()`. It is always guaranteed to be the proper instance, at any point in time.
@ -81,7 +81,7 @@ It's as simple as:
this.refs.myInput
```
### Completing the Example
## Completing the Example
```javascript
var App = React.createClass({
@ -115,7 +115,7 @@ It's as simple as:
In this example, our render function returns a description of an <input/> instance. But the true instance is accessed via `this.refs.theInput`. As long as a child component with `ref="theInput"` is returned from render, `this.refs.theInput` will access the the proper instance. This even works on higher level (non-DOM) components such as <Typeaheadref="myTypeahead"/>.
### Summary
## Summary
Refs are a great way to send a message to a particular child instance in a way that would be inconvenient to do via streaming Reactive `props` and `state`. They should, however, not be your go-to abstraction for flowing data through your application. By default, use the Reactive data flow and save `ref`s for use cases that are inherently non-reactive.
Every project uses a different system for building and deploying JavaScript. We've tried to make React as environment-agnostic as possible.
### CDN-hosted React
## CDN-hosted React
We provide CDN-hosted versions of React [on our download page](/react/downloads.html). These prebuilt files use the UMD module format. Dropping them in with a simple `<script>` tag will inject a `React` global into your environment. It also works out-of-the-box in CommonJS and AMD environments.
### Using master
## Using Master
We have instructions for building from master [in our GitHub repository](https://github.com/facebook/react). We build a tree of CommonJS modules under `build/modules` which you can drop into any environment or packaging tool that supports CommonJS.
### In-browser JSX transform
## In-browser JSX Transform
If you like using JSX, we provide an in-browser JSX transformer for development [on our download page](/react/downloads.html). Simply include a `<script type="text/jsx">` tag to engage the JSX transformer. Be sure to include the `/** @jsx React.DOM */` comment as well, otherwise the transformer will not run the transforms.
**Warning:** the in-browser JSX transformer is fairly large and is extra computation. Do not use it in production -- see the next section.
### Productionizing: precompiled JSX
## Productionizing: Precompiled JSX
If you have [npm](http://npmjs.org/), you can simply run `npm install -g react-tools` to install our command-line `jsx` tool. This tool will translate files that use JSX syntax to plain JavaScript files that can run directly in the browser. It will also watch directories for you and automatically transform files when they are changed; for example: `jsx --watch src/ build/`. Run `jsx --help` for more information on how to use this tool.
### Helpful open-source projects
## Helpful Open-Source Projects
The open-source community has built tools that integrate JSX with several build systems.
* [React one-hour email](https://github.com/petehunt/react-one-hour-email/commits/master) goes step-by-step from a static HTML mock to an interactive email reader (written in just one hour!)
* [Rendr + React app template](https://github.com/petehunt/rendr-react-template/) demonstrates how to use React's server rendering capabilities.
### API
## API
#### React
### React
`React` is the entry point to the React framework. If you're using one of the prebuilt packages it's available as a global; if you're using CommonJS modules you can `require()` it.
##### React.DOM
#### React.DOM
`React.DOM` provides all of the standard HTML tags needed to build a React app. You generally don't use it directly; instead, just include it as part of the `/** @jsx React.DOM */` docblock.
Configure React's event system to handle touch events on mobile devices.
##### React.createClass
#### React.createClass
```javascript
function createClass(object specification)
@ -47,7 +47,7 @@ function createClass(object specification)
Creates a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than a standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
@ -57,7 +57,7 @@ Renders a React component into the DOM in the supplied `container`.
If the React component was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
Remove a mounted React component from the DOM and clean up its event handlers and state.
##### React.renderComponentToString
#### React.renderComponentToString
```javascript
renderComponentToString(ReactComponent component, function callback)
@ -73,17 +73,17 @@ renderComponentToString(ReactComponent component, function callback)
Render a component to its initial HTML. This should only be used on the server. React will call `callback` with an HTML string when the markup is ready. You can use this method to create static site generators, or you can generate HTML on the server and send it down to have a very fast initial page load. If you call `React.renderComponent()` 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.
#### AbstractEvent
### AbstractEvent
Your event handlers will be passed instances of `AbstractEvent`, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event (such as `stopPropagation()` and `preventDefault()`) except they work exactly the same across all browsers.
If you find that you need the underlying browser event for some reason, simply use the `nativeEvent` attribute to get it.
#### ReactComponent
### ReactComponent
Component classses created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming `ReactComponent`s.
##### getDOMNode
#### getDOMNode
```javascript
DOMElement getDOMNode()
@ -91,7 +91,7 @@ DOMElement getDOMNode()
If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
##### setProps
#### setProps
```javascript
setProps(object nextProps)
@ -101,7 +101,7 @@ When you're integrating with an external JavaScript application you may want to
**Note:** This method can only be called on a root-level component. That is, it's only available on the component passed directly to `renderComponent()` and none of its children. If you're inclined to use `setProps()` on a child component, instead take advantage of reactive updates and pass the new prop to the child component when it's created in `render()`.
##### replaceProps
#### replaceProps
```javascript
replaceProps(object nextProps)
@ -109,7 +109,7 @@ replaceProps(object nextProps)
Like `setProps()` but deletes any pre-existing props that are not in nextProps.
Transfer properties from this component to a target component that have not already been set on the target component. This is usually used to pass down properties to the returned root component. `targetComponent`, now updated with some new props is returned as a convenience.
##### setState
#### setState
```javascript
setState(object nextState[, function callback])
@ -131,7 +131,7 @@ Merges nextState with the current state. This is the primary method you use to t
**Note**: There is no guarantee of synchronous operation of calls to `setState` and calls may be batched for performance gains.
##### replaceState
#### replaceState
```javascript
replaceState(object nextState[, function callback])
@ -139,7 +139,7 @@ replaceState(object nextState[, function callback])
Like `setState()` but deletes any pre-existing state keys that are not in nextState.
##### forceUpdate()
#### forceUpdate()
```javascript
forceUpdate([function callback])
@ -151,7 +151,7 @@ Normally you should try to avoid all uses of `forceUpdate()` and only read from
**Note**: There is no guarantee of synchronous operation of calls to `forceUpdate` and calls may be batched for performance gains.
##### Lifecycle methods
#### Lifecycle methods
```javascript
object getInitialState()
@ -167,7 +167,7 @@ componentWillUnmount()
See the [working with the browser](./07-working-with-the-browser.html) documentation for more details on these lifecycle methods.
### DOM differences
## DOM Differences
React has implemented a browser-independent events and DOM system for performance and cross-browser compatibility reasons. We took the opportunity to clean up a few rough edges in browser DOM implementations.