Fix title casing and heading levels

This commit is contained in:
Paul O’Shannessy 2013-07-16 14:52:57 -07:00
parent 04bfa545f7
commit 9694a0f7ea
13 changed files with 109 additions and 109 deletions

View File

@ -2,7 +2,7 @@
<div class="nav-docs-section">
<h3>Quick start</h3>
<ul>
<li><a href="/react/docs/getting-started.html"{% if page.id == 'getting-started' %} class="active"{% endif %}>Getting started</a></li>
<li><a href="/react/docs/getting-started.html"{% if page.id == 'getting-started' %} class="active"{% endif %}>Getting Started</a></li>
<li><a href="/react/docs/tutorial.html"{% if page.id == 'tutorial' %} class="active"{% endif %}>Tutorial</a></li>
</ul>
</div>
@ -10,13 +10,13 @@
<h3>Guides</h3>
<ul>
<li><a href="/react/docs/01-why-react.html"{% if page.id == '01-why-react' %} class="active"{% endif %}>Why React?</a></li>
<li><a href="/react/docs/02-displaying-data.html"{% if page.id == '02-displaying-data' %} class="active"{% endif %}>Displaying data</a></li>
<li><a href="/react/docs/03-interactivity-and-dynamic-uis.html"{% if page.id == '03-interactivity-and-dynamic-uis' %} class="active"{% endif %}>Interactivity and dynamic UIs</a></li>
<li><a href="/react/docs/04-multiple-components.html"{% if page.id == '04-multiple-components' %} class="active"{% endif %}>Multiple components</a></li>
<li><a href="/react/docs/05-reusable-components.html"{% if page.id == '05-reusable-components' %} class="active"{% endif %}>Reusable components</a></li>
<li><a href="/react/docs/02-displaying-data.html"{% if page.id == '02-displaying-data' %} class="active"{% endif %}>Displaying Data</a></li>
<li><a href="/react/docs/03-interactivity-and-dynamic-uis.html"{% if page.id == '03-interactivity-and-dynamic-uis' %} class="active"{% endif %}>Interactivity and Dynamic UIs</a></li>
<li><a href="/react/docs/04-multiple-components.html"{% if page.id == '04-multiple-components' %} class="active"{% endif %}>Multiple Components</a></li>
<li><a href="/react/docs/05-reusable-components.html"{% if page.id == '05-reusable-components' %} class="active"{% endif %}>Reusable Components</a></li>
<li><a href="/react/docs/06-forms.html"{% if page.id == '06-forms' %} class="active"{% endif %}>Forms</a></li>
<li><a href="/react/docs/07-working-with-the-browser.html"{% if page.id == '07-working-with-the-browser' %} class="active"{% endif %}>Working with the browser</a></li>
<li><a href="/react/docs/08-tooling-integration.html"{% if page.id == '08-tooling-integration' %} class="active"{% endif %}>Tooling integration</a></li>
<li><a href="/react/docs/07-working-with-the-browser.html"{% if page.id == '07-working-with-the-browser' %} class="active"{% endif %}>Working With the Browser</a></li>
<li><a href="/react/docs/08-tooling-integration.html"{% if page.id == '08-tooling-integration' %} class="active"{% endif %}>Tooling Integration</a></li>
<li><a href="/react/docs/09-reference.html"{% if page.id == '09-reference' %} class="active"{% endif %}>Reference</a></li>
</ul>

View File

@ -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).

View File

@ -1,13 +1,13 @@
---
id: 02-displaying-data
title: Displaying data
title: Displaying Data
layout: docs
prev: 01-why-react.html
next: 02.1-jsx-in-depth.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.

View File

@ -8,7 +8,7 @@ next: 02.2-jsx-gotchas.html
JSX is a JavaScript XML syntax transform recommended (but not required) for use
with React.
### Why JSX?
## Why JSX?
First of all, **don't use JSX if you don't like it!**
@ -25,7 +25,7 @@ We recommend using JSX for many reasons:
- Designers are more comfortable making changes.
- It's familiar for those who have used MXML or XAML.
### The Transform
## The Transform
JSX transforms XML-like syntax into native JavaScript. It turns XML elements and
attributes into function calls and objects, respectively.
@ -61,7 +61,7 @@ how to setup compilation.
> Details about the code transform are given here to increase understanding, but
> your code should not rely on these implementation details.
### React and JSX
## React and JSX
React and JSX are independent technologies, but JSX was primarily built with
React in mind. The two valid uses of JSX are:
@ -97,7 +97,7 @@ See [Component Basics](component-basics.html) to learn more about components.
> as XML attribute names. Instead, React DOM components expect attributes like
> `className` and `htmlFor`, respectively.
### DOM Convenience
## DOM Convenience
Having to define variables for every type of DOM element can get tedious
(e.g. `var div, span, h1, h2, ...`). JSX provides a convenience to address this
@ -121,9 +121,9 @@ var tree = Nav(null, React.DOM.span(null, null));
> DOM. The docblock parameter is only a convenience to resolve the most commonly
> used elements. In general, JSX has no notion of the DOM.
### JavaScript Expressions
## JavaScript Expressions
##### Attribute Expressions
### Attribute Expressions
To use a JavaScript expression as an attribute value, wrap the expression in a
pair of curly braces (`{}`) instead of quotes (`""`).
@ -135,7 +135,7 @@ var person = <Person name={window.isLoggedIn ? window.name : ''} />;
var person = Person({name: window.isLoggedIn ? window.name : ''});
```
##### Child Expressions
### Child Expressions
Likewise, JavaScript expressions may be used to express children:
@ -146,14 +146,14 @@ var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
var content = Container(null, window.isLoggedIn ? Nav(null, null) : Login(null, null));
```
##### Comments
### Comments
It's easy to add comments within your JSX; they're just JS expressions:
```javascript
var content = <Container>{/* this is a comment */}<Nav /></Container>;
```
### Tooling
## Tooling
Beyond the compilation step, JSX does not require any special tools.
@ -162,7 +162,7 @@ Beyond the compilation step, JSX does not require any special tools.
- Elements use standard scoping so linters can find usage of out-of-scope
components.
### Prior Work
## Prior Work
JSX is similar to several other JavaScript embedded XML language
proposals/projects. Some of the features of JSX that distinguish it from similar
@ -172,4 +172,4 @@ efforts include:
- JSX neither provides nor requires a runtime library.
- JSX does not alter or add to the semantics of JavaScript.
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](./02.2-jsx-gotchas.html) for some key differences.
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](./02.2-jsx-gotchas.html) for some key differences.

View File

@ -7,7 +7,7 @@ next: 03-interactivity-and-dynamic-uis.html
---
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.
<div dangerouslySetInnerHTML={{'{{'}}__html: 'First &middot; Second'}} />
```
### Custom HTML Attributes
## Custom HTML Attributes
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-`.
@ -69,4 +69,4 @@ If you pass properties to native HTML elements that do not exist in the HTML spe
```javascript
<div aria-hidden={true} />
```
```

View File

@ -7,7 +7,7 @@ next: 04-multiple-components.html
---
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,14 +67,14 @@ 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:
* **Computed data.** Don't worry about precomputing values based on state -- it's easier to ensure that your UI is consistent if you do all computation within `render()`. For example, if you have an array of list items in state and you want to render the count as a string, simply render `this.state.listItems.length + ' list items'` in your `render()` method rather than storing it on state.
* **React components.** Build them in `render()` based on underlying props and state.
* **Duplicated data from props.** Try to use props as the source of truth where possible. Because props can change over time, it's appropriate to store props in state to be able to know its previous values.
* **Duplicated data from props.** Try to use props as the source of truth where possible. Because props can change over time, it's appropriate to store props in state to be able to know its previous values.

View File

@ -1,17 +1,17 @@
---
id: 04-multiple-components
title: Multiple components
title: Multiple Components
layout: docs
prev: 03-interactivity-and-dynamic-uis.html
next: 05-reusable-components.html
---
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
<Card><p style={{display: 'none'}}>Paragraph 1</p><p>Paragraph 2</p></Card>
```
#### Dynamic Children
### Dynamic Children
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,14 +116,14 @@ 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.
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React API docs](./api.html) for more information.
**Note:** if `shouldComponentUpdate()` returns false when data has actually changed, React can't keep your UI in sync. Be sure you know what you're doing while using it, and only use this function when you have a noticeable performance problem. Don't underestimate how fast JavaScript is relative to the DOM.
**Note:** if `shouldComponentUpdate()` returns false when data has actually changed, React can't keep your UI in sync. Be sure you know what you're doing while using it, and only use this function when you have a noticeable performance problem. Don't underestimate how fast JavaScript is relative to the DOM.

View File

@ -1,19 +1,19 @@
---
id: 05-reusable-components
title: Reusable components
title: Reusable Components
layout: docs
prev: 04-multiple-components.html
next: 06-forms.html
---
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.
### Testing
## Testing
**TODO: benjamn**
**TODO: benjamn**

View File

@ -7,7 +7,7 @@ next: 07-working-with-the-browser.html
---
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:
@ -121,4 +121,4 @@ For HTML, this easily allows developers to supply multiline values. However, sin
<textarea name="description" value="This is a description." />
```
If you *do* decide to use children, they will behave like `defaultValue`.
If you *do* decide to use children, they will behave like `defaultValue`.

View File

@ -1,13 +1,13 @@
---
id: 07-working-with-the-browser
title: Working with the browser
title: Working With the Browser
layout: docs
prev: 06-forms.html
next: 07.1-more-about-refs.html
---
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).
#### Polyfills needed to support older browsers
### Polyfills Needed to Support Older Browsers
* `Array.isArray`
* `Array.prototype.forEach`
@ -115,4 +115,4 @@ In addition to that philosphy, we've also taken the stance that we, as authors o
All of these can be polyfilled using `es5-shim.js` from [https://github.com/kriskowal/es5-shim](https://github.com/kriskowal/es5-shim).
* `console.*` - [https://github.com/paulmillr/console-polyfill](https://github.com/paulmillr/console-polyfill)
* `Object.create` - Provided in `es5-sham.js` @ [https://github.com/kriskowal/es5-shim](https://github.com/kriskowal/es5-shim)
* `Object.create` - Provided in `es5-sham.js` @ [https://github.com/kriskowal/es5-shim](https://github.com/kriskowal/es5-shim)

View File

@ -1,6 +1,6 @@
---
id: 07.1-more-about-refs
title: More about refs
title: More About Refs
layout: docs
prev: 07-working-with-the-browser.html
next: 08-tooling-integration.html
@ -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 <Typeahead ref="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.
@ -132,4 +132,4 @@ Refs are automatically book-kept for you! If that child is destroyed, its ref is
- If you want to preserve Google Closure Compiler Crushing resilience, make sure to never access as a property what was specified as a string. This means you must access using `this.refs['myRefString']` if your ref was defined as `ref="myRefString"`.
- If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where `state` should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use `ref`s to "make things happen" - instead, the data flow will usually accomplish your goal.
- If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where `state` should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use `ref`s to "make things happen" - instead, the data flow will usually accomplish your goal.

View File

@ -7,29 +7,29 @@ next: 09-reference.html
---
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.
* [reactify](https://github.com/andreypopp/reactify) - use JSX with [browserify](http://browserify.org/).
* [grunt-react](https://github.com/ericclemmons/grunt-react) - [grunt](http://gruntjs.com/) task for JSX
* [require-jsx](https://github.com/seiffert/require-jsx) - use JSX with [require.js](http://requirejs.org/)
* [reactapp](https://github.com/jordwalke/reactapp) - a sample project to get up-and-running with React quickly
* [reactapp](https://github.com/jordwalke/reactapp) - a sample project to get up-and-running with React quickly

View File

@ -4,15 +4,15 @@ title: Reference
layout: docs
prev: 08-tooling-integration.html
---
### Examples
## Examples
#### Production apps
### Production Apps
* All of [Instagram.com](http://instagram.com/) is built on React.
* Many components on [Facebook.com](http://www.facebook.com/), including the commenting interface, ads creation flows, and page insights.
* [Khan Academy](http://khanacademy.org/) is using React for its question editor.
#### Sample code
### Sample Code
* We've included **[a step-by-step comment box tutorial](./tutorial.md)**
* There is also [a simple LikeButton tutorial](./likebutton/)
@ -21,17 +21,17 @@ prev: 08-tooling-integration.html
* [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.
##### React.initializeTouchEvents
#### React.initializeTouchEvents
```javascript
initializeTouchEvents(boolean shouldUseTouch)
@ -39,7 +39,7 @@ initializeTouchEvents(boolean shouldUseTouch)
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.
##### React.renderComponent
#### React.renderComponent
```javascript
ReactComponent renderComponent(ReactComponent container, DOMElement container)
@ -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.
##### React.unmountAndReleaseReactRootNode
#### React.unmountAndReleaseReactRootNode
```javascript
unmountAndReleaseReactRootNode(DOMElement container)
@ -65,7 +65,7 @@ unmountAndReleaseReactRootNode(DOMElement container)
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.
##### transferPropsTo
#### transferPropsTo
```javascript
ReactComponent transferPropsTo(ReactComponent targetComponent)
@ -117,7 +117,7 @@ ReactComponent transferPropsTo(ReactComponent targetComponent)
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.