Browse Source

add seconds 02.1 and 03

main
petehunt 12 years ago
parent
commit
c3f99be8fe
  1. 1
      docs/refactor/00-table-of-contents.md
  2. 157
      docs/refactor/02-displaying-data.md
  3. 161
      docs/refactor/02.1-jsx-in-depth.md
  4. 59
      docs/refactor/03-handling-user-input.md

1
docs/refactor/00-table-of-contents.md

@ -14,6 +14,7 @@ Handling user input
- Under the hood: autoBind and event delegation (IE8 notes)
- How state works
- What should go in state?
- What components should have state?
Scaling up: using multiple components
- Motivation: separate concerns

157
docs/refactor/02-displaying-data.md

@ -53,163 +53,12 @@ setInterval(function() {
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.
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**.
## 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.
We've found that the best solution for this problem is to generate markup directly from the JavaScript code such that you can use all of the expressive power of a real programming language to build UIs. In order to make this easier, we've added a *very* simple, **optional** HTML-like syntax for the function calls that generate markup called JSX.
### Don't use JSX if you don't like it!
React works out of the box without JSX. Simply construct your markup using the
functions on `React.DOM`. For example, here's how to construct a simple link:
```javascript
var link = React.DOM.a({href: 'http://facebook.github.io/react'}, 'React');
```
However, we recommend using JSX for many reasons:
- It's easier to visualize the structure of the DOM.
- Designers are more comfortable making changes.
- It's familiar for those who have used MXML or XAML.
### The Transform
JSX transforms XML-like syntax into native JavaScript. It turns XML elements and
attributes into function calls and objects, respectively.
```javascript
var Nav;
// Input (JSX):
var app = <Nav color="blue" />;
// Output (JS):
var app = Nav({color:'blue'}, null);
```
Notice that in order to use `<Nav />`, the `Nav` variable must be in scope.
JSX also allows specifying children using XML syntax:
```javascript
var Nav, Profile;
// Input (JSX):
var app = <Nav color="blue"><Profile>click</Profile></Nav>;
// Output (JS):
var app = Nav({color:'blue'}, Profile(null, 'click'));
```
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
desugars into native JavaScript.
If you want to use JSX, the [Getting Started](getting-started.html) guide shows
how to setup compilation.
> Note:
>
> 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 are independent technologies, but JSX was primarily built with
React in mind. The two valid uses of JSX are:
- To construct instances of React DOM components (`React.DOM.*`).
- To construct instances of composite components created with
`React.createClass()`.
**React DOM Components**
To construct a `<div>` is to create a variable that refers to `React.DOM.div`.
```javascript
var div = React.DOM.div;
var app = <div className="appClass">Hello, React!</div>;
```
**React Component Components**
To construct an instance of a composite component, create a variable that
references the class.
```javascript
var MyComponent = React.createClass({/*...*/});
var app = <MyComponent someProperty={true} />;
```
See [Component Basics](component-basics.html) to learn more about components.
> Note:
>
> Since JSX is JavaScript, identifiers such as `class` and `for` are discouraged
> as XML attribute names. Instead, React DOM components expect attributes like
> `className` and `htmlFor`, respectively.
### 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
problem by allowing you to specify a variable in an `@jsx` docblock field. JSX
will use that field to find DOM components.
```javascript
/**
* @jsx React.DOM
*/
var Nav;
// Input (JSX):
var tree = <Nav><span /></Nav>;
// Output (JS):
var tree = Nav(null, React.DOM.span(null, null));
```
> Remember:
>
> JSX simply transforms elements into function calls and has no notion of the
> 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
#### Attribute Expressions
To use a JavaScript expression as an attribute value, wrap the expression in a
pair of curly braces (`{}`) instead of quotes (`""`).
```javascript
// Input (JSX):
var person = <Person name={window.isLoggedIn ? window.name : ''} />;
// Output (JS):
var person = Person({name: window.isLoggedIn ? window.name : ''});
```
#### Child Expressions
Likewise, JavaScript expressions may be used to express children:
```javascript
// Input (JSX):
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
// Output (JS):
var content = Container(null, window.isLoggedIn ? Nav(null, null) : Login(null, null));
```
### Tooling
Beyond the compilation step, JSX does not require any special tools.
- Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
- Linting provides accurate line numbers after compiling without sourcemaps.
- Elements use standard scoping so linters can find usage of out-of-scope
components.
### 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
efforts include:
- JSX is a simple syntactic transform.
- JSX neither provides nor requires a runtime library.
- JSX does not alter or add to the semantics of JavaScript.
JSX is very small; the example above uses every feature of JSX. To learn more about it, see [JSX in depth](./02.1-jsx-in-depth.md)

161
docs/refactor/02.1-jsx-in-depth.md

@ -0,0 +1,161 @@
# JSX in Depth
JSX is a JavaScript XML syntax transform recommended (but not required) for use
with React.
## Why JSX?
First of all, **don't use JSX if you don't like it!**
React works out of the box without JSX. Simply construct your markup using the
functions on `React.DOM`. For example, here's how to construct a simple link:
```javascript
var link = React.DOM.a({href: 'http://facebook.github.io/react'}, 'React');
```
We recommend using JSX for many reasons:
- It's easier to visualize the structure of the DOM.
- Designers are more comfortable making changes.
- It's familiar for those who have used MXML or XAML.
## The Transform
JSX transforms XML-like syntax into native JavaScript. It turns XML elements and
attributes into function calls and objects, respectively.
```javascript
var Nav;
// Input (JSX):
var app = <Nav color="blue" />;
// Output (JS):
var app = Nav({color:'blue'}, null);
```
Notice that in order to use `<Nav />`, the `Nav` variable must be in scope.
JSX also allows specifying children using XML syntax:
```javascript
var Nav, Profile;
// Input (JSX):
var app = <Nav color="blue"><Profile>click</Profile></Nav>;
// Output (JS):
var app = Nav({color:'blue'}, Profile(null, 'click'));
```
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
desugars into native JavaScript.
If you want to use JSX, the [Getting Started](getting-started.html) guide shows
how to setup compilation.
> Note:
>
> 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 are independent technologies, but JSX was primarily built with
React in mind. The two valid uses of JSX are:
- To construct instances of React DOM components (`React.DOM.*`).
- To construct instances of composite components created with
`React.createClass()`.
**React DOM Components**
To construct a `<div>` is to create a variable that refers to `React.DOM.div`.
```javascript
var div = React.DOM.div;
var app = <div className="appClass">Hello, React!</div>;
```
**React Component Components**
To construct an instance of a composite component, create a variable that
references the class.
```javascript
var MyComponent = React.createClass({/*...*/});
var app = <MyComponent someProperty={true} />;
```
See [Component Basics](component-basics.html) to learn more about components.
> Note:
>
> Since JSX is JavaScript, identifiers such as `class` and `for` are discouraged
> as XML attribute names. Instead, React DOM components expect attributes like
> `className` and `htmlFor`, respectively.
## 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
problem by allowing you to specify a variable in an `@jsx` docblock field. JSX
will use that field to find DOM components.
```javascript
/**
* @jsx React.DOM
*/
var Nav;
// Input (JSX):
var tree = <Nav><span /></Nav>;
// Output (JS):
var tree = Nav(null, React.DOM.span(null, null));
```
> Remember:
>
> JSX simply transforms elements into function calls and has no notion of the
> 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
#### Attribute Expressions
To use a JavaScript expression as an attribute value, wrap the expression in a
pair of curly braces (`{}`) instead of quotes (`""`).
```javascript
// Input (JSX):
var person = <Person name={window.isLoggedIn ? window.name : ''} />;
// Output (JS):
var person = Person({name: window.isLoggedIn ? window.name : ''});
```
#### Child Expressions
Likewise, JavaScript expressions may be used to express children:
```javascript
// Input (JSX):
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
// Output (JS):
var content = Container(null, window.isLoggedIn ? Nav(null, null) : Login(null, null));
```
## Tooling
Beyond the compilation step, JSX does not require any special tools.
- Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
- Linting provides accurate line numbers after compiling without sourcemaps.
- Elements use standard scoping so linters can find usage of out-of-scope
components.
## 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
efforts include:
- JSX is a simple syntactic transform.
- JSX neither provides nor requires a runtime library.
- JSX does not alter or add to the semantics of JavaScript.

59
docs/refactor/03-handling-user-input.md

@ -0,0 +1,59 @@
# Handling User Input
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
```javascript
/** @jsx React.DOM */
var LikeButton = React.createClass({
getInitialState: function() {
return {liked: false};
},
handleClick: function(event) {
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'unlike';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
</p>
);
}
});
React.renderComponent(
<LikeButton />,
document.getElementById('example')
);
```
## 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.
## Under the hood: autoBind and event delegation
Under the hood React does a few things to keep your code performant and easy to understand.
**Autobinding.** Every method is automatically bound to its component instance. React caches the bound method such that it's extremely CPU and memory efficient. It's also less typing!
**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
## 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 state tends to be so minimal.
## 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.
**Try to keep as many of your components as possible stateless.** By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.
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?
**`this.state` should contain any data that the component's event handlers will change that should 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.
Loading…
Cancel
Save