Compare commits
61 Commits
yeswork
...
0.10-stabl
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d5b409002b | ||
|
|
9d4baa12a6 | ||
|
|
0606de0db7 | ||
|
|
13817753c6 | ||
|
|
3f37e8e4ab | ||
|
|
fe1b554d9d | ||
|
|
0ecf9f0599 | ||
|
|
acba66fe2e | ||
|
|
661bafb059 | ||
|
|
8f0c1ce7b1 | ||
|
|
3ca2ab8960 | ||
|
|
06844c27a8 | ||
|
|
b2ea0d0e29 | ||
|
|
90682ad1ee | ||
|
|
617de48e53 | ||
|
|
fd4143a198 | ||
|
|
224b6e5a6a | ||
|
|
11707179da | ||
|
|
bfecabf71a | ||
|
|
bcaebecce2 | ||
|
|
6055468d1c | ||
|
|
7ea026e19a | ||
|
|
f7e4667457 | ||
|
|
e88c0b1b1f | ||
|
|
950ecd84ff | ||
|
|
66b027233c | ||
|
|
c28cd1ae1a | ||
|
|
321643a858 | ||
|
|
c29f1823a1 | ||
|
|
424ebb5436 | ||
|
|
94c6396853 | ||
|
|
f832b9ce59 | ||
|
|
d6c5058193 | ||
|
|
59c495511a | ||
|
|
ba717cfc62 | ||
|
|
9af5b6b1c3 | ||
|
|
35321a8908 | ||
|
|
d90046a104 | ||
|
|
d28467796c | ||
|
|
cff284f291 | ||
|
|
7818b9f81f | ||
|
|
76b2e87173 | ||
|
|
a8aa901e1b | ||
|
|
f45ab7c7f4 | ||
|
|
383e385d51 | ||
|
|
bb3916448e | ||
|
|
5936173626 | ||
|
|
1400085fe3 | ||
|
|
6d2dd794ee | ||
|
|
0247d9d625 | ||
|
|
d160715b19 | ||
|
|
5f6d46f696 | ||
|
|
e197768058 | ||
|
|
f893442591 | ||
|
|
c14a26e573 | ||
|
|
6210dd3325 | ||
|
|
1acdd51af3 | ||
|
|
bf6fe2c194 | ||
|
|
e65085846f | ||
|
|
dedf0c20da | ||
|
|
12bdb8d24c |
24
CHANGELOG.md
24
CHANGELOG.md
@@ -1,3 +1,27 @@
|
||||
## 0.10.0 (March 21, 2014)
|
||||
|
||||
### React Core
|
||||
|
||||
#### New Features
|
||||
* Added warnings to help migrate towards descriptors
|
||||
* Made it possible to server render without React-related markup (`data-reactid`, `data-react-checksum`). This DOM will not be mountable by React. [Read the docs for `React.renderComponentToStaticMarkup`](http://facebook.github.io/react/docs/top-level-api.html#react.rendercomponenttostaticmarkup)
|
||||
* Added support for more attributes:
|
||||
* `srcSet` for `<img>` to specify images at different pixel ratios
|
||||
* `textAnchor` for SVG
|
||||
|
||||
#### Bug Fixes
|
||||
* Ensure all void elements don’t insert a closing tag into the markup.
|
||||
* Ensure `className={false}` behaves consistently
|
||||
* Ensure `this.refs` is defined, even if no refs are specified.
|
||||
|
||||
### Addons
|
||||
|
||||
* `update` function to deal with immutable data. [Read the docs](http://facebook.github.io/react/docs/update.html)
|
||||
|
||||
### react-tools
|
||||
* Added an option argument to `transform` function. The only option supported is `harmony`, which behaves the same as `jsx --harmony` on the command line. This uses the ES6 transforms from [jstransform](https://github.com/facebook/jstransform).
|
||||
|
||||
|
||||
## 0.9.0 (February 20, 2014)
|
||||
|
||||
### React Core
|
||||
|
||||
@@ -40,12 +40,12 @@ The fastest way to get started is to serve JavaScript from the CDN (also availab
|
||||
|
||||
```html
|
||||
<!-- The core React library -->
|
||||
<script src="http://fb.me/react-0.9.0.js"></script>
|
||||
<script src="http://fb.me/react-0.10.0.js"></script>
|
||||
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
|
||||
<script src="http://fb.me/JSXTransformer-0.9.0.js"></script>
|
||||
<script src="http://fb.me/JSXTransformer-0.10.0.js"></script>
|
||||
```
|
||||
|
||||
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.9.0.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
|
||||
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.10.0.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
|
||||
|
||||
If you'd like to use [bower](http://bower.io), it's as easy as:
|
||||
|
||||
|
||||
8
docs/404.md
Normal file
8
docs/404.md
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
layout: single
|
||||
title: Page Not Found
|
||||
---
|
||||
|
||||
We couldn't find what you were looking for.
|
||||
|
||||
Please contact the owner of the site that linked you to the original URL and let them know their link is broken.
|
||||
@@ -13,7 +13,7 @@ redcarpet:
|
||||
pygments: true
|
||||
name: React
|
||||
markdown: redcarpet
|
||||
react_version: 0.10.0-alpha
|
||||
react_version: 0.10.0
|
||||
description: A JavaScript library for building user interfaces
|
||||
relative_permalinks: true
|
||||
paginate: 5
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
@import '_solarized';
|
||||
|
||||
@mixin code-typography {
|
||||
font-family: 'source-code-pro', Menlo, 'Courier New', Consolas, monospace;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
font-family: 'source-code-pro', Menlo, Consolas, 'Courier New', monospace;
|
||||
font-size: 0.8em;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
$skinnyContentWidth: 650px;
|
||||
@@ -683,7 +683,12 @@ p code {
|
||||
}
|
||||
|
||||
.highlight pre code {
|
||||
font-size: inherit;
|
||||
/* Respect line-height defined in <code> styles above */
|
||||
display: block;
|
||||
|
||||
/* Cancel out styles for `li code` in case we have a <pre> within an <li>. */
|
||||
background: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.highlight pre .lineno {
|
||||
|
||||
@@ -73,3 +73,9 @@
|
||||
title: Special Non-DOM Attributes
|
||||
- id: reconciliation
|
||||
title: Reconciliation
|
||||
- title: Flux
|
||||
items:
|
||||
- id: flux-overview
|
||||
title: Flux Overview
|
||||
- id: flux-todo-list
|
||||
title: Flux Todo List
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
<![endif]-->
|
||||
<script type="text/javascript" src="/react/js/codemirror.js"></script>
|
||||
<script type="text/javascript" src="/react/js/javascript.js"></script>
|
||||
<script type="text/javascript" src="/react/js/react.min.js"></script>
|
||||
<script type="text/javascript" src="/react/js/react.js"></script>
|
||||
<script type="text/javascript" src="/react/js/JSXTransformer.js"></script>
|
||||
<script type="text/javascript" src="/react/js/live_editor.js"></script>
|
||||
<script type="text/javascript" src="/react/js/showdown.js"></script>
|
||||
|
||||
@@ -19,7 +19,5 @@ sectionid: docs
|
||||
<a class="docs-next" href="/react/docs/{{ page.next }}">Next →</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="fb-comments" data-width="650" data-num-posts="10" data-href="{{ site.url }}{{ site.baseurl }}{{ page.url }}"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -16,6 +16,5 @@ sectionid: blog
|
||||
</div>
|
||||
|
||||
<div class="fb-like" data-send="true" data-width="650" data-show-faces="false"></div>
|
||||
<div class="fb-comments" data-width="650" data-num-posts="10" data-href="{{ site.url }}{{ site.baseurl }}{{ page.url }}"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -19,7 +19,5 @@ sectionid: tips
|
||||
<a class="docs-next" href="/react/tips/{{ page.next }}">Next →</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="fb-comments" data-width="650" data-num-posts="10" data-href="{{ site.url }}{{ site.baseurl }}{{ page.url }}"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -75,7 +75,7 @@ some pretty cool things with it:
|
||||
- We've built internal prototypes that run React apps in a web worker and use
|
||||
React to drive **native iOS views** via an Objective-C bridge.
|
||||
- You can run React
|
||||
[on the server](http://github.com/petehunt/react-server-rendering)
|
||||
[on the server](http://github.com/petehunt/react-server-rendering-example)
|
||||
for SEO, performance, code sharing and overall flexibility.
|
||||
- Events behave in a consistent, standards-compliant way in all browsers
|
||||
(including IE8) and automatically use
|
||||
|
||||
@@ -22,7 +22,7 @@ We're looking forward to part 2!
|
||||
|
||||
## React vs. async DOM manipulation
|
||||
|
||||
Eliseu Monar ([@eliseumds](https://twitter.com/eliseumds))'s post "[ReactJS vs async concurrent rendering](http://eliseu.tk/post/77843550010/vitalbox-pchr-reactjs-vs-async-concurrent-rendering)" is a great example of how React quite literally renders a whole array of common web development work(arounds) obsolete.
|
||||
Eliseu Monar ([@eliseumds](https://twitter.com/eliseumds))'s post "[ReactJS vs async concurrent rendering](http://eliseumds.tumblr.com/post/77843550010/vitalbox-pchr-reactjs-vs-async-concurrent-rendering)" is a great example of how React quite literally renders a whole array of common web development work(arounds) obsolete.
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -8,13 +8,13 @@ author: Paul O’Shannessy
|
||||
|
||||
The release candidate is available for download from the CDN:
|
||||
|
||||
* **React**
|
||||
Dev build with warnings: <http://fb.me/react-0.10.0-rc1.js>
|
||||
Minified build for production: <http://fb.me/react-0.10.0-rc1.min.js>
|
||||
* **React with Add-Ons**
|
||||
Dev build with warnings: <http://fb.me/react-with-addons-0.10.0-rc1.js>
|
||||
Minified build for production: <http://fb.me/react-with-addons-0.10.0-rc1.min.js>
|
||||
* **In-Browser JSX transformer**
|
||||
* **React**
|
||||
Dev build with warnings: <http://fb.me/react-0.10.0-rc1.js>
|
||||
Minified build for production: <http://fb.me/react-0.10.0-rc1.min.js>
|
||||
* **React with Add-Ons**
|
||||
Dev build with warnings: <http://fb.me/react-with-addons-0.10.0-rc1.js>
|
||||
Minified build for production: <http://fb.me/react-with-addons-0.10.0-rc1.min.js>
|
||||
* **In-Browser JSX transformer**
|
||||
<http://fb.me/JSXTransformer-0.10.0-rc1.js>
|
||||
|
||||
We've also published version `0.10.0-rc1` of the `react` and `react-tools` packages on npm and the `react` package on bower.
|
||||
@@ -53,9 +53,10 @@ The plan for v0.11 is that we will go fully to "descriptors". Method calls on th
|
||||
### React Core
|
||||
|
||||
#### New Features
|
||||
* Made it possible to server render without React-related markup (`data-reactid`, `data-react-checksum`) - `React.renderComponentToStaticMarkup`
|
||||
* Added warnings to help migrate towards descriptors
|
||||
* Made it possible to server render without React-related markup (`data-reactid`, `data-react-checksum`). This DOM will not be mountable by React. [Read the docs for `React.renderComponentToStaticMarkup`](/react/docs/top-level-api.html#react.rendercomponenttostaticmarkup)
|
||||
* Added support for more attributes:
|
||||
* `srcSet` for `<img>` to images at different pixel ratios
|
||||
* `srcSet` for `<img>` to specify images at different pixel ratios
|
||||
* `textAnchor` for SVG
|
||||
|
||||
#### Bug Fixes
|
||||
@@ -65,7 +66,7 @@ The plan for v0.11 is that we will go fully to "descriptors". Method calls on th
|
||||
|
||||
### Addons
|
||||
|
||||
* `update` function to deal with immutable data.
|
||||
* `update` function to deal with immutable data. [Read the docs](/react/docs/update.html)
|
||||
|
||||
### react-tools
|
||||
* Added an option argument to `transform` function. The only option supported is `harmony`, which behaves the same as `jsx --harmony` on the command line. This uses the ES6 transforms from [jstransform](https://github.com/facebook/jstransform).
|
||||
|
||||
73
docs/_posts/2014-03-21-react-v0.10.md
Normal file
73
docs/_posts/2014-03-21-react-v0.10.md
Normal file
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: React v0.10
|
||||
layout: post
|
||||
author: Paul O’Shannessy
|
||||
---
|
||||
|
||||
Hot on the heels of the [release candidate earlier this week](/react/blog/2014/03/19/react-v0.10-rc1.html), we're ready to call v0.10 done. The only major issue we discovered had to do with the `react-tools` package, which has been updated. We've copied over the changelog from the RC with some small clarifying changes.
|
||||
|
||||
The release is available for download from the CDN:
|
||||
|
||||
* **React**
|
||||
Dev build with warnings: <http://fb.me/react-0.10.0.js>
|
||||
Minified build for production: <http://fb.me/react-0.10.0.min.js>
|
||||
* **React with Add-Ons**
|
||||
Dev build with warnings: <http://fb.me/react-with-addons-0.10.0.js>
|
||||
Minified build for production: <http://fb.me/react-with-addons-0.10.0.min.js>
|
||||
* **In-Browser JSX transformer**
|
||||
<http://fb.me/JSXTransformer-0.10.0.js>
|
||||
|
||||
We've also published version `0.10.0` of the `react` and `react-tools` packages on npm and the `react` package on bower.
|
||||
|
||||
Please try these builds out and [file an issue on GitHub](https://github.com/facebook/react/issues/new) if you see anything awry.
|
||||
|
||||
## Clone On Mount
|
||||
|
||||
The main purpose of this release is to provide a smooth upgrade path as we evolve some of the implementation of core. In v0.9 we started warning in cases where you called methods on unmounted components. This is part of an effort to enforce the idea that the return value of a component (`React.DOM.div()`, `MyComponent()`) is in fact not a reference to the component instance React uses in the virtual DOM. The return value is instead a light-weight object that React knows how to use. Since the return value currently is a reference to the same object React uses internally, we need to make this transition in stages as many people have come to depend on this implementation detail.
|
||||
|
||||
In 0.10, we’re adding more warnings to catch a similar set of patterns. When a component is mounted we clone it and use that object for our internal representation. This allows us to capture calls you think you’re making to a mounted component. We’ll forward them on to the right object, but also warn you that this is breaking. See “Access to the Mounted Instance” on [this page](http://fb.me/react-warning-descriptors). Most of the time you can solve your pattern by using refs.
|
||||
|
||||
Storing a reference to your top level component is a pattern touched upon on that page, but another examples that demonstrates what we see a lot of:
|
||||
|
||||
```js
|
||||
// This is a common pattern. However instance here really refers to a
|
||||
// "descriptor", not necessarily the mounted instance.
|
||||
var instance = <MyComponent/>;
|
||||
React.renderComponent(instance);
|
||||
// ...
|
||||
instance.setProps(...);
|
||||
|
||||
// The change here is very simple. The return value of renderComponent will be
|
||||
// the mounted instance.
|
||||
var instance = React.renderComponent(<MyComponent/>)
|
||||
// ...
|
||||
instance.setProps(...);
|
||||
```
|
||||
|
||||
These warnings and method forwarding are only enabled in the development build. The production builds continue to work as they did in v0.9. We strongly encourage you to use the development builds to catch these warnings and fix the call sites.
|
||||
|
||||
The plan for v0.11 is that we will go fully to "descriptors". Method calls on the return value of `MyComponent()` will fail hard.
|
||||
|
||||
## Changelog
|
||||
|
||||
### React Core
|
||||
|
||||
#### New Features
|
||||
* Added warnings to help migrate towards descriptors
|
||||
* Made it possible to server render without React-related markup (`data-reactid`, `data-react-checksum`). This DOM will not be mountable by React. [Read the docs for `React.renderComponentToStaticMarkup`](/react/docs/top-level-api.html#react.rendercomponenttostaticmarkup)
|
||||
* Added support for more attributes:
|
||||
* `srcSet` for `<img>` to specify images at different pixel ratios
|
||||
* `textAnchor` for SVG
|
||||
|
||||
#### Bug Fixes
|
||||
* Ensure all void elements don’t insert a closing tag into the markup.
|
||||
* Ensure `className={false}` behaves consistently
|
||||
* Ensure `this.refs` is defined, even if no refs are specified.
|
||||
|
||||
### Addons
|
||||
|
||||
* `update` function to deal with immutable data. [Read the docs](/react/docs/update.html)
|
||||
|
||||
### react-tools
|
||||
* Added an option argument to `transform` function. The only option supported is `harmony`, which behaves the same as `jsx --harmony` on the command line. This uses the ES6 transforms from [jstransform](https://github.com/facebook/jstransform).
|
||||
|
||||
57
docs/_posts/2014-03-28-the-road-to-1.0.md
Normal file
57
docs/_posts/2014-03-28-the-road-to-1.0.md
Normal file
@@ -0,0 +1,57 @@
|
||||
---
|
||||
title: The Road to 1.0
|
||||
layout: post
|
||||
author: Paul O'Shannessy
|
||||
---
|
||||
|
||||
When we launched React last spring, we purposefully decided not to call it 1.0. It was production ready, but we had plans to evolve APIs and behavior as we saw how people were using React, both internally and externally. We've learned a lot over the past 9 months and we've thought a lot about what 1.0 will mean for React. A couple weeks ago, I outlined [several projects][projects] that we have planned to take us to 1.0 and beyond. Today I'm writing a bit more about them to give our users a better insight into our plans.
|
||||
|
||||
Our primary goal with 1.0 is to clarify our messaging and converge on an API that is aligned with our goals. In order to do that, we want to clean up bad patterns we've seen in use and really help enable developers write good code.
|
||||
|
||||
## Descriptors
|
||||
|
||||
The first part of this is what we're calling "descriptors". I talked about this briefly in our [v0.10 announcements][v0.10]. The goal here is to separate our virtual DOM representation from our use of it. Simply, this means the return value of a component (e.g. `React.DOM.div()`, `MyComponent()`) will be a simple object containing the information React needs to render. Currently the object returned is actually linked to React's internal representation of the component and even directly to the DOM element. This has enabled some bad patterns that are quite contrary to how we want people to use React. That's our failure.
|
||||
|
||||
We added some warnings in v0.9 to start migrating some of these bad patterns. With v0.10 we'll catch more. You'll see more on this soon as we expect to ship v0.11 with descriptors.
|
||||
|
||||
## API Cleanup
|
||||
|
||||
This is really connected to everything. We want to keep the API as simple as possible and help developers [fall into the pit of success][pitofsuccess]. Enabling bad patterns with bad APIs is not success.
|
||||
|
||||
## ES6
|
||||
|
||||
Before we even launched React publicly, members of the team were talking about how we could leverage ES6, namely classes, to improve the experience of creating React components. Calling `React.createClass(...)` isn't great. We don't quite have the right answer here yet, but we're close. We want to make sure we make this as simple as possible. It could look like this:
|
||||
|
||||
```js
|
||||
class MyComponent extends React.Component {
|
||||
render() {
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
There are other features of ES6 we're already using in core. I'm sure we'll see more of that. The `jsx` executable we ship with `react-tools` already supports transforming many parts of ES6 into code that will run on older browsers.
|
||||
|
||||
## Context
|
||||
|
||||
While we haven't documented `context`, it exists in some form in React already. It exists as a way to pass values through a tree without having to use props at every single point. We've seen this need crop up time and time again, so we want to make this as easy as possible. It's use has performance tradeoffs, and there are known weaknesses in our implementation, so we want to make sure this is a solid feature.
|
||||
|
||||
## Addons
|
||||
|
||||
As you may know, we ship a separate build of React with some extra features we called "addons". While this has served us fine, it's not great for our users. It's made testing harder, but also results in more cache misses for people using a CDN. The problem we face is that many of these "addons" need access to parts of React that we don't expose publicly. Our goal is to ship each addon on its own and let each hook into React as needed. This would also allow others to write and distribute "addons".
|
||||
|
||||
## Browser Support
|
||||
|
||||
As much as we'd all like to stop supporting older browsers, it's not always possible. Facebook still supports IE8. While React won't support IE8 forever, our goal is to have 1.0 support IE8. Hopefully we can continue to abstract some of these rough parts.
|
||||
|
||||
## Animations
|
||||
|
||||
Finding a way to define animations in a declarative way is a hard problem. We've been exploring the space for a long time. We've introduced some half-measures to alleviate some use cases, but the larger problem remains. While we'd like to make this a part of 1.0, realistically we don't think we'll have a good solution in place.
|
||||
|
||||
## Miscellaneous
|
||||
|
||||
There are several other things I listed on [our projects page][projects] that we're tracking. Some of them are internals and have no obvious outward effect (improve tests, repo separation, updated test runner). I encourage you to take a look.
|
||||
|
||||
[v0.10]: http://facebook.github.io/react/blog/2014/03/21/react-v0.10.html
|
||||
[pitofsuccess]: http://blog.codinghorror.com/falling-into-the-pit-of-success/
|
||||
[projects]: https://github.com/facebook/react/wiki/Projects
|
||||
38
docs/_posts/2014-04-04-reactnet.md
Normal file
38
docs/_posts/2014-04-04-reactnet.md
Normal file
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: "Use React and JSX in ASP.NET MVC"
|
||||
layout: post
|
||||
author: Daniel Lo Nigro
|
||||
---
|
||||
|
||||
Today we're happy to announce the initial release of
|
||||
[ReactJS.NET](http://reactjs.net/), which makes it easier to use React and JSX
|
||||
in .NET applications, focusing specifically on ASP.NET MVC web applications.
|
||||
It has several purposes:
|
||||
|
||||
- On-the-fly JSX to JavaScript compilation. Simply reference JSX files and they
|
||||
will be compiled and cached server-side.
|
||||
|
||||
```html
|
||||
<script src="@Url.Content("/Scripts/HelloWorld.jsx")"></script>
|
||||
```
|
||||
- JSX to JavaScript compilation via popular minification/combination libraries
|
||||
(Cassette and ASP.NET Bundling and Minification). This is suggested for
|
||||
production websites.
|
||||
- Server-side component rendering to make your initial render super fast.
|
||||
|
||||
Even though we are focusing on ASP.NET MVC, ReactJS.NET can also be used in
|
||||
Web Forms applications as well as non-web applications (for example, in build
|
||||
scripts). ReactJS.NET currently only works on Microsoft .NET but we are working
|
||||
on support for Linux and Mac OS X via Mono as well.
|
||||
|
||||
Installation
|
||||
------------
|
||||
ReactJS.NET is packaged in NuGet. Simply run `Install-Package React.Mvc4` in the
|
||||
package manager console or search NuGet for "React" to install it.
|
||||
[See the documentation](http://reactjs.net/docs) for more information. The
|
||||
GitHub project contains
|
||||
[a sample website](https://github.com/reactjs/React.NET/tree/master/src/React.Sample.Mvc4)
|
||||
demonstrating all of the features.
|
||||
|
||||
Let us know what you think, and feel free to send through any feedback and
|
||||
report bugs [on GitHub](https://github.com/reactjs/React.NET).
|
||||
17
docs/_posts/2014-05-06-flux.md
Normal file
17
docs/_posts/2014-05-06-flux.md
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: "Flux: An Application Architecture for React"
|
||||
layout: post
|
||||
author: Bill Fisher and Jing Chen
|
||||
---
|
||||
|
||||
We recently spoke at one of f8's breakout session about Flux, a data flow architecture that works well with React. Check out the video here:
|
||||
|
||||
<figure><iframe width="560" height="315" src="//www.youtube.com/embed/nYkdrAPrdcw?list=PLb0IAmt7-GS188xDYE-u1ShQmFFGbrk0v" frameborder="0" allowfullscreen></iframe></figure>
|
||||
|
||||
To summarize, Flux works well for us because the single directional data flow makes it easy to understand and modify an application as it becomes more complicated. We found that two-way data bindings lead to cascading updates, where changing one data model led to another data model updating, making it very difficult to predict what would change as the result of a single user interaction.
|
||||
|
||||
In Flux, the Dispatcher is a singleton that directs the flow of data and ensures that updates do not cascade. As an application grows, the Dispatcher becomes more vital, as it can also manage dependencies between stores by invoking the registered callbacks in a specific order.
|
||||
|
||||
When a user interacts with a React view, the view sends an action (usually represented as a JavaScript object with some fields) through the dispatcher, which notifies the various stores that hold the application's data and business logic. When the stores change state, they notify the views that something has updated. This works especially well with React's declarative model, which allows the stores to send updates without specifying how to transition views between states.
|
||||
|
||||
Flux is more of a pattern than a formal framework, so you can start using Flux immediately without a lot of new code. An [example of this architecture](https://github.com/facebook/react/tree/master/examples/todomvc-flux) is available, along with more [detailed documentation](http://facebook.github.io/react/docs/flux-overview.html) and a [tutorial](http://facebook.github.io/react/docs/flux-todo-list.html). Look for more examples to come in the future.
|
||||
15
docs/_posts/2014-05-29-one-year-of-open-source-react.md
Normal file
15
docs/_posts/2014-05-29-one-year-of-open-source-react.md
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
title: "One Year of Open-Source React"
|
||||
layout: post
|
||||
author: Cheng Lou
|
||||
---
|
||||
|
||||
Today marks the one-year open-source anniversary of React.
|
||||
|
||||
It’s been a crazy ride. 2.3k commits and 1.5k issues and pull requests later, we’re approaching version 1.0 and nearing 7k Github stars, with big names such as Khan Academy, New York Times, and Airbnb (and naturally, Facebook and Instagram) using React in production, and many more developers blogging their success stories with it. The [roadmap](http://facebook.github.io/react/blog/2014/03/28/the-road-to-1.0.html) gives a glimpse into the future of the library; exciting stuff lies ahead!
|
||||
|
||||
Every success has its story. React was born out of our frustration at existing solutions for building UIs. When it was first suggested at Facebook, few people thought that functionally re-rendering everything and diffing the results could ever perform well. However, support grew after we built the first implementation and people wrote their first components. When we open-sourced React, the initial reception was [similarly skeptical](http://www.reddit.com/r/programming/comments/1fak87/react_facebooks_latest_javascript_client_library/). It challenges many pre-established conventions and received mostly disapproving first-impressions, intermingled with positive ones that often were votes of confidence in Facebook’s engineering capabilities. On an open, competitive platform such as the web, it's been hard to convince people to try React. [JSX](http://facebook.github.io/react/docs/jsx-in-depth.html), in particular, filtered out a huge chunk of potential early adopters.
|
||||
|
||||
Fast forward one year, React has strongly [grown in popularity](https://news.ycombinator.com/item?id=7489959). Special acknowledgments go to Khan Academy, the ClojureScript community, and established frameworks such as Ember and Angular for contributing to and debating on our work. We'd also like to thank all the [individual contributors](https://github.com/facebook/react/graphs/contributors) who have taken the time to help out over the past year. React, as a library and as a new paradigm on the web, wouldn't have gained as much traction without them. In the future, we will continue to try to set an example of what's possible to achieve when we rethink about current “best practices”.
|
||||
|
||||
Here’s to another year!
|
||||
55
docs/_posts/2014-06-27-community-roundup-19.md
Normal file
55
docs/_posts/2014-06-27-community-roundup-19.md
Normal file
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: "Community Round-up #19"
|
||||
layout: post
|
||||
author: Cheng Lou
|
||||
---
|
||||
|
||||
## React Meetups!
|
||||
Ever wanted to find developers who also share the same interest in React than you? Recently, there has been a React Meetup in [San Francisco](http://www.meetup.com/ReactJS-San-Francisco/) (courtesy of [Telmate](http://www.telmate.com)), and one in [London](http://www.meetup.com/London-React-User-Group/) (courtesy of [Stuart Harris](http://www.meetup.com/London-React-User-Group/members/105837542/), [Cain Ullah](http://www.meetup.com/London-React-User-Group/members/15509971/) and [Zoe Merchant](http://www.meetup.com/London-React-User-Group/members/137058242/)). These two events have been big successes; a second one in London is [already planned](http://www.meetup.com/London-React-User-Group/events/191406572/).
|
||||
|
||||
If you don't live near San Francisco or London, why not start one in your community?
|
||||
|
||||
## Complementary Tools
|
||||
In case you haven't seen it, we've consolidated the tooling solution around React on [this wiki page](https://github.com/facebook/react/wiki/Complementary-Tools). Some of the notable recent entries include:
|
||||
|
||||
- [Ryan Florence](https://github.com/rpflorence) and [Michael Jackson](https://github.com/mjackson)'s [react-nested-router](https://github.com/rpflorence/react-nested-router), which is a translation of the Ember router API to React.
|
||||
|
||||
- [Stephen J. Collings](https://github.com/stevoland)'s [react-bootstrap](https://github.com/react-bootstrap/react-bootstrap), which wraps the popular framework with a bit of React goodness. The [website](http://react-bootstrap.github.io/components.html) features live-editable demos.
|
||||
|
||||
- [Andrey Popp](https://github.com/andreypopp)'s [react-quickstart](https://github.com/andreypopp/react-quickstart), which gives you a quick template for server-side rendering and routing, among other features.
|
||||
|
||||
These are some of the links that often pop up on the #reactjs IRC channel. If you made something that you think deserves to be shown on the wiki, feel free to add it!
|
||||
|
||||
## React in Interesting Places
|
||||
|
||||
The core concepts React themselves is something very valuable that the community is exploring and pushing further. A year ago, we wouldn't have imagined something like [Bruce Hauman](http://rigsomelight.com)'s [Flappy Bird ClojureScript port](http://rigsomelight.com/2014/05/01/interactive-programming-flappy-bird-clojurescript.html), whose interactive programming has been made possible through React:
|
||||
|
||||
<iframe width="560" height="315" src="//www.youtube.com/embed/KZjFVdU8VLI" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
And don't forget [Pete Hunt](https://github.com/petehunt)'s Wolfenstein 3D rendering engine in React ([source code](https://github.com/petehunt/wolfenstein3D-react/blob/master/js/renderer.js#L183)). While it's nearly a year old, it's still a nice demo.
|
||||
|
||||
[](http://www.petehunt.net/wolfenstein3D-react/wolf3d.html)
|
||||
|
||||
Give us a shoutout on IRC or [React Google Groups](https://groups.google.com/forum/#!forum/reactjs) if you've used React in some Interesting places.
|
||||
|
||||
## Even More People Using React
|
||||
|
||||
### Prismatic
|
||||
[Prismatic](http://getprismatic.com/home) recently shrank their codebase fivefold with the help of React and its popular ClojureScript wrapper, [Om](https://github.com/swannodette/om). They detailed their very positive experience [here](http://blog.getprismatic.com/om-sweet-om-high-functional-frontend-engineering-with-clojurescript-and-react/).
|
||||
|
||||
> Finally, the state is normalized: each piece of information is represented in a single place. Since React ensures consistency between the DOM and the application data, the programmer can focus on ensuring that the state properly stays up to date in response to user input. If the application state is normalized, then this consistency is guaranteed by definition, completely avoiding the possibility of an entire class of common bugs.
|
||||
|
||||
### Adobe Brackets
|
||||
[Kevin Dangoor](http://www.kevindangoor.com) works on [Brackets](http://brackets.io/?lang=en), the open-source code editor. After writing [his first impression on React](http://www.kevindangoor.com/2014/05/simplifying-code-with-react/), he followed up with another insightful [article](http://www.kevindangoor.com/2014/05/react-in-brackets/) on how to gradually make the code transition, how to preserve the editor's good parts, and how to tune Brackets' tooling around JSX.
|
||||
|
||||
> We don’t need to switch to React everywhere, all at once. It’s not a framework that imposes anything on the application structure. [...] Easy, iterative adoption is definitely something in React’s favor for us.
|
||||
|
||||
### Storehouse
|
||||
[Storehouse](https://www.storehouse.co) (Apple Design Award 2014)'s web presence is build with React. Here's [an example story](https://www.storehouse.co/stories/y2ad-mexico-city-clouds). Congratulations on the award!
|
||||
|
||||
### Vim Awesome
|
||||
[Vim Awesome](http://vimawesome.com), an open-source Vim plugins directory built on React, was just launched. Be sure to [check out the source code](https://github.com/divad12/vim-awesome) if you're curious to see an example of how to build a small single-page React app.
|
||||
|
||||
## Random Tweets
|
||||
|
||||
<blockquote class="twitter-tweet" lang="en"><p>Spent 12 hours so far with <a href="https://twitter.com/hashtag/reactjs?src=hash">#reactjs</a>. Spent another 2 wondering why we've been doing JS frameworks wrong until now. React makes me happy.</p>— Paul Irwin (@paulirwin) <a href="https://twitter.com/paulirwin/statuses/481263947589242882">June 24, 2014</a></blockquote>
|
||||
147
docs/_posts/2014-07-13-react-v0.11-rc1.md
Normal file
147
docs/_posts/2014-07-13-react-v0.11-rc1.md
Normal file
@@ -0,0 +1,147 @@
|
||||
---
|
||||
title: React v0.11 RC
|
||||
layout: post
|
||||
author: Paul O’Shannessy
|
||||
---
|
||||
|
||||
It's that time again… we're just about ready to ship a new React release! v0.11 includes a wide array of bug fixes and features. We highlighted some of the most important changes below, along with the full changelog.
|
||||
|
||||
The release candidate is available for download from the CDN:
|
||||
|
||||
* **React**
|
||||
Dev build with warnings: <http://fb.me/react-0.11.0-rc1.js>
|
||||
Minified build for production: <http://fb.me/react-0.11.0-rc1.min.js>
|
||||
* **React with Add-Ons**
|
||||
Dev build with warnings: <http://fb.me/react-with-addons-0.11.0-rc1.js>
|
||||
Minified build for production: <http://fb.me/react-with-addons-0.11.0-rc1.min.js>
|
||||
* **In-Browser JSX transformer**
|
||||
<http://fb.me/JSXTransformer-0.11.0-rc1.js>
|
||||
|
||||
We've also published version `0.11.0-rc1` of the `react` and `react-tools` packages on npm and the `react` package on bower.
|
||||
|
||||
Please try these builds out and [file an issue on GitHub](https://github.com/facebook/react/issues/new) if you see anything awry.
|
||||
|
||||
|
||||
# Blog Post
|
||||
|
||||
## `getDefaultProps`
|
||||
|
||||
Starting in React 0.11, `getDefaultProps()` is called only once when `React.createClass()` is called, instead of each time a component is rendered. This means that `getDefaultProps()` can no longer vary its return value based on `this.props` and any objects will be shared across all instances. This change improves performance and will make it possible in the future to do PropTypes checks earlier in the rendering process, allowing us to give better error messages.
|
||||
|
||||
|
||||
## Rendering to `null`
|
||||
|
||||
Since React's release, people have been using work arounds to "render nothing". Usually this means returning an empty `<div/>` or `<span/>`. Some people even got clever and started returning `<noscript/>` to avoid extraneous DOM nodes. We finally provided a "blessed" solution that allows developers to writing meaningful code. Returning `null` in an explicit indication to React that you do not want anything rendered. Behind the scenes we make this work with a `<noscript>` element, though in the future we hope to not put anything in the document. In the mean time, `<noscript>` elements do not affect layout in any way, so you can feel safe using `null` today!
|
||||
|
||||
```js
|
||||
// Before
|
||||
render: function() {
|
||||
if (!this.state.visible) {
|
||||
return <span/>;
|
||||
}
|
||||
// ...
|
||||
}
|
||||
|
||||
// After
|
||||
render: function() {
|
||||
if (!this.state.visible) {
|
||||
return null;
|
||||
}
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## JSX Namespacing
|
||||
|
||||
Another feature request we've been hearing for a long time is the ability to have namespaces in JSX. Given that JSX is just JavaScript, we didn't want to use XML namespacing. Instead we opted for a standard JS approach: object property access. Instead of assigning variables to access components stored in an object (such as a component library), you can now use the component directly as `<Namespace.Component/>`.
|
||||
|
||||
```js
|
||||
// Before
|
||||
var UI = require('UI');
|
||||
var UILayout = UI.Layout;
|
||||
var UIButton = UI.Button;
|
||||
var UILabel = UI.Label;
|
||||
|
||||
render: function() {
|
||||
return <UILayout><UIButton /><UILabel>text</UILabel></UILayout>;
|
||||
}
|
||||
|
||||
// After
|
||||
var UI = require('UI');
|
||||
|
||||
render: function() {
|
||||
return <UI.Layout><UI.Button /><UI.Label>text</UI.Label></UI.Layout>;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Improved keyboard event normalization
|
||||
|
||||
Keyboard events now contain a normalized `e.key` value according to the [DOM Level 3 Events spec](http://www.w3.org/TR/DOM-Level-3-Events/#keys-special), allowing you to write simpler key handling code that works in all browsers, such as:
|
||||
|
||||
```js
|
||||
handleKeyDown: function(e) {
|
||||
if (e.key === 'Enter') {
|
||||
// Handle enter key
|
||||
} else if (e.key === ' ') {
|
||||
// Handle spacebar
|
||||
} else if (e.key === 'ArrowLeft') {
|
||||
// Handle left arrow
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
Keyboard and mouse events also now include a normalized `e.getModifierState()` that works consistently across browsers.
|
||||
|
||||
## Changelog
|
||||
|
||||
### React Core
|
||||
|
||||
#### Breaking Changes
|
||||
* `getDefaultProps()` is now called once per class and shared across all instances
|
||||
|
||||
#### New Features
|
||||
* Rendering to `null`
|
||||
* Keyboard events include normalized `e.key` and `e.getModifierState()` properties
|
||||
* New normalized `onBeforeInput` event
|
||||
* `React.Children.count` has been added as a helper for counting the number of children
|
||||
|
||||
#### Bug Fixes
|
||||
|
||||
* Re-renders are batched in more cases
|
||||
* Events: `e.view` properly normalized
|
||||
* Added Support for more HTML attributes (`coords`, `crossOrigin`, `download`, `hrefLang`, `mediaGroup`, `muted`, `scrolling`, `shape`, `srcSet`, `start`, `useMap`)
|
||||
* Improved SVG support
|
||||
* Changing `className` on a mounted SVG component now works correctly
|
||||
* Added support for elements `mask` and `tspan`
|
||||
* Added support for attributes `dx`, `dy`, `fillOpacity`, `fontFamily`, `fontSize`, `markerEnd`, `markerMid`, `markerStart`, `opacity`, `patternContentUnits`, `patternUnits`, `preserveAspectRatio`, `strokeDasharray`, `strokeOpacity`
|
||||
* CSS property names with vendor prefixes (`Webkit`, `ms`, `Moz`, `O`) are now handled properly
|
||||
* Duplicate keys no longer cause a hard error; now a warning is logged (and only one of the children with the same key is shown)
|
||||
* `img` event listeners are now unbound properly, preventing the error "Two valid but unequal nodes with the same `data-reactid`"
|
||||
* Added explicit warning when missing polyfills
|
||||
|
||||
### React With Addons
|
||||
* PureRenderMixin
|
||||
* Perf: a new set of tools to help with performance analysis
|
||||
* Update: New `$apply` command to transform values
|
||||
* TransitionGroup bug fixes with null elements, Android
|
||||
|
||||
### React NPM Module
|
||||
* Now includes the pre-built packages under `dist/`.
|
||||
* `envify` is properly listed as a dependency instead of a peer dependency
|
||||
|
||||
### JSX
|
||||
* Added support for namespaces, eg `<Components.Checkbox />`
|
||||
* JSXTransformer
|
||||
* Enable the same `harmony` features available in the command line with `<script type="text/jsx;harmony=true">`
|
||||
* Scripts are downloaded in parallel for more speed. They are still executed in order (as you would expect with normal script tags)
|
||||
* Fixed a bug preventing sourcemaps from working in Firefox
|
||||
|
||||
### React Tools Module
|
||||
* Improved readme with usage and API information
|
||||
* Improved ES6 transforms available with `--harmony` option
|
||||
* Added `--source-map-inline` option to the `jsx` executable
|
||||
* New `transformWithDetails` API which gives access to the raw sourcemap data
|
||||
|
||||
|
||||
@@ -124,4 +124,4 @@ We'd like to thank all of our contributors:
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
In addition, we're grateful to [Jeff Barczewski](https://github.com/jeffbski) for allowing us to use the `react` package name on npm.
|
||||
In addition, we're grateful to [Jeff Barczewski](https://github.com/jeffbski) for allowing us to use the [react](https://www.npmjs.org/package/react) package name on npm and to [Christopher Aue](http://christopheraue.net/) for letting us use the [reactjs.com](http://reactjs.com/) domain name and the [@reactjs](https://twitter.com/reactjs) username on Twitter.
|
||||
|
||||
@@ -20,7 +20,7 @@ sectionid: blog
|
||||
|
||||
<div class="pagination">
|
||||
{% if paginator.previous_page %}
|
||||
<a href="/react/{{ paginator.previous_page_path }}" class="previous">
|
||||
<a href="/react{{ paginator.previous_page_path }}" class="previous">
|
||||
« Previous Page
|
||||
</a>
|
||||
{% endif %}
|
||||
|
||||
@@ -161,10 +161,20 @@ var content = Container(null, window.isLoggedIn ? Nav(null) : Login(null));
|
||||
|
||||
### Comments
|
||||
|
||||
It's easy to add comments within your JSX; they're just JS expressions:
|
||||
It's easy to add comments within your JSX; they're just JS expressions. You just need to be careful to put `{}` around the comments when you are within the children section of a tag.
|
||||
|
||||
```javascript
|
||||
var content = <Container>{/* this is a comment */}<Nav /></Container>;
|
||||
var content = (
|
||||
<Nav>
|
||||
{/* child comment, put {} around */}
|
||||
<Person
|
||||
/* multi
|
||||
line
|
||||
comment */
|
||||
name={window.isLoggedIn ? window.name : ''} // end of line comment
|
||||
/>
|
||||
</Nav>
|
||||
);
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ React.createClass({
|
||||
// shown if the prop isn't provided.
|
||||
requiredFunc: React.PropTypes.func.isRequired,
|
||||
|
||||
// An object of any kind
|
||||
// A value of any data type
|
||||
requiredAny: React.PropTypes.any.isRequired,
|
||||
|
||||
// You can also specify a custom validator.
|
||||
|
||||
@@ -9,6 +9,7 @@ next: 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.
|
||||
|
||||
For information on events on `<form>` see [Form Events](/react/docs/events.html#form-events).
|
||||
|
||||
## Interactive Props
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ Consider the case when you wish to tell an `<input />` element (that exists with
|
||||
getInitialState: function() {
|
||||
return {userInput: ''};
|
||||
},
|
||||
handleKeyUp: function(e) {
|
||||
handleChange: function(e) {
|
||||
this.setState({userInput: e.target.value});
|
||||
},
|
||||
clearAndFocusInput: function() {
|
||||
@@ -26,11 +26,11 @@ Consider the case when you wish to tell an `<input />` element (that exists with
|
||||
return (
|
||||
<div>
|
||||
<div onClick={this.clearAndFocusInput}>
|
||||
Click To Focus and Reset
|
||||
Click to Focus and Reset
|
||||
</div>
|
||||
<input
|
||||
value={this.state.userInput}
|
||||
onKeyUp={this.handleKeyUp}
|
||||
onChange={this.handleChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -72,17 +72,19 @@ React supports a very special property that you can attach to any component that
|
||||
|
||||
It's as simple as:
|
||||
|
||||
**1.** Assign a `ref` attribute to anything returned from `render` such as:
|
||||
1. Assign a `ref` attribute to anything returned from `render` such as:
|
||||
|
||||
```html
|
||||
<input ref="myInput" />
|
||||
```
|
||||
```html
|
||||
<input ref="myInput" />
|
||||
```
|
||||
|
||||
**2.** In some other code (typically event handler code), access the **backing instance** via `this.refs` as in:
|
||||
2. In some other code (typically event handler code), access the **backing instance** via `this.refs` as in:
|
||||
|
||||
```javascript
|
||||
```javascript
|
||||
this.refs.myInput
|
||||
```
|
||||
```
|
||||
|
||||
You can access the component's DOM node directly by calling `this.refs.myInput.getDOMNode()`.
|
||||
|
||||
## Completing the Example
|
||||
|
||||
@@ -91,23 +93,26 @@ It's as simple as:
|
||||
getInitialState: function() {
|
||||
return {userInput: ''};
|
||||
},
|
||||
handleKeyUp: function(e) {
|
||||
handleChange: function(e) {
|
||||
this.setState({userInput: e.target.value});
|
||||
},
|
||||
clearAndFocusInput: function() {
|
||||
this.setState({userInput: ''}); // Clear the input
|
||||
this.refs.theInput.getDOMNode().focus(); // Boom! Focused!
|
||||
// Clear the input
|
||||
this.setState({userInput: ''}, function() {
|
||||
// This code executes after the component is re-rendered
|
||||
this.refs.theInput.getDOMNode().focus(); // Boom! Focused!
|
||||
});
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div>
|
||||
<div onClick={this.clearAndFocusInput}>
|
||||
Click To Focus and Reset
|
||||
Click to Focus and Reset
|
||||
</div>
|
||||
<input
|
||||
ref="theInput"
|
||||
value={this.state.userInput}
|
||||
onKeyUp={this.handleKeyUp}
|
||||
onChange={this.handleChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -132,4 +137,4 @@ Refs are a great way to send a message to a particular child instance in a way t
|
||||
|
||||
- *Never* access refs inside of any component's render method - or while any component's render method is even running anywhere in the call stack.
|
||||
- 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.
|
||||
|
||||
@@ -38,18 +38,4 @@ If you have [npm](http://npmjs.org/), you can simply run `npm install -g react-t
|
||||
|
||||
### Helpful Open-Source Projects
|
||||
|
||||
The open-source community has built tools that integrate JSX with several build systems. See [JSX integrations](/react/docs/complementary-tools.html#jsx-integrations) for the full list.
|
||||
|
||||
|
||||
### Syntax Highlighting & Linting
|
||||
|
||||
* Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
|
||||
* [JSX syntax highlighting](https://github.com/yungsters/sublime/blob/master/tmLanguage/JavaScript%20(JSX\).tmLanguage) is available for Sublime Text and other editors
|
||||
that support `*.tmLanguage`.
|
||||
* [web-mode.el](http://web-mode.org) is an autonomous emacs major mode that indents and highlights JSX
|
||||
* Linting provides accurate line numbers after compiling without sourcemaps.
|
||||
* Elements use standard scoping so linters can find usage of out-of-scope components.
|
||||
|
||||
### Debugging
|
||||
|
||||
[React Developer Tools](https://github.com/facebook/react-devtools) is a [Chrome extension](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) that allows you to inspect the React component hierarchy in the Chrome Developer Tools.
|
||||
The open-source community has built tools that integrate JSX with several editors and build systems. See [JSX integrations](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations) for the full list.
|
||||
|
||||
@@ -17,7 +17,7 @@ React provides a `ReactTransitionGroup` addon component as a low-level API for a
|
||||
|
||||
`ReactCSSTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out.
|
||||
|
||||
```javascript{22-24}
|
||||
```javascript{30-32}
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
|
||||
@@ -33,7 +33,7 @@ var TodoList = React.createClass({
|
||||
},
|
||||
handleRemove: function(i) {
|
||||
var newItems = this.state.items;
|
||||
newItems.splice(i, 1)
|
||||
newItems.splice(i, 1);
|
||||
this.setState({items: newItems});
|
||||
},
|
||||
render: function() {
|
||||
@@ -46,7 +46,7 @@ var TodoList = React.createClass({
|
||||
}.bind(this));
|
||||
return (
|
||||
<div>
|
||||
<div><button onClick={this.handleAdd} /></div>
|
||||
<button onClick={this.handleAdd}>Add Item</button>
|
||||
<ReactCSSTransitionGroup transitionName="example">
|
||||
{items}
|
||||
</ReactCSSTransitionGroup>
|
||||
|
||||
@@ -12,17 +12,18 @@ next: clone-with-props.html
|
||||
### Simulate
|
||||
|
||||
```javascript
|
||||
Simulate.{eventName}({ReactComponent|DOMElement} element, object eventData)
|
||||
Simulate.{eventName}(DOMElement element, object eventData)
|
||||
```
|
||||
|
||||
Simulate an event dispatch on a React component instance or browser DOM node with optional `eventData` event data. **This is possibly the single most useful utility in `ReactTestUtils`.**
|
||||
Simulate an event dispatch on a DOM node with optional `eventData` event data. **This is possibly the single most useful utility in `ReactTestUtils`.**
|
||||
|
||||
Example usage:
|
||||
|
||||
```javascript
|
||||
React.addons.TestUtils.Simulate.click(myComponent);
|
||||
React.addons.TestUtils.Simulate.change(myComponent);
|
||||
React.addons.TestUtils.Simulate.keydown(myComponent, {key: "Enter"});
|
||||
var node = this.refs.input.getDOMNode();
|
||||
React.addons.TestUtils.Simulate.click(node);
|
||||
React.addons.TestUtils.Simulate.change(node);
|
||||
React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"});
|
||||
```
|
||||
|
||||
`Simulate` has a method for every event that React understands.
|
||||
@@ -94,7 +95,7 @@ Traverse all components in `tree` and accumulate all components where `test(comp
|
||||
### scryRenderedDOMComponentsWithClass
|
||||
|
||||
```javascript
|
||||
array scryRenderedDOMComponentsWithClass(ReactCompoennt tree, string className)
|
||||
array scryRenderedDOMComponentsWithClass(ReactComponent tree, string className)
|
||||
```
|
||||
|
||||
Finds all instance of components in the rendered tree that are DOM components with the class name matching `className`.
|
||||
|
||||
@@ -7,54 +7,4 @@ prev: videos.html
|
||||
next: examples.html
|
||||
---
|
||||
|
||||
React is a small library that does one thing well. Here's a list of tools we've found that work really well with React when building applications.
|
||||
|
||||
If you want your project on this list, or think one of these projects should be removed, [open an issue on GitHub](https://github.com/facebook/react/issues/new).
|
||||
|
||||
### JSX integrations
|
||||
|
||||
* **[jsxhint](https://npmjs.org/package/jsxhint)** [JSHint](http://jshint.com/) (linting) support.
|
||||
* **[reactify](https://npmjs.org/package/reactify)** [Browserify](http://browserify.org/) transform.
|
||||
* **[node-jsx](https://npmjs.org/package/node-jsx)** Native [Node](http://nodejs.org/) support.
|
||||
* **[jsx-loader](https://npmjs.org/package/jsx-loader)** Loader for [webpack](http://webpack.github.io/).
|
||||
* **[grunt-react](https://npmjs.org/package/grunt-react)** [GruntJS](http://gruntjs.com/) task.
|
||||
* **[gulp-react](https://npmjs.org/package/gulp-react)** [GulpJS](http://gulpjs.com/) plugin.
|
||||
* **[jsx-requirejs-plugin](https://github.com/philix/jsx-requirejs-plugin)** [RequireJS](http://requirejs.org/) plugin.
|
||||
* **[react-meteor](https://github.com/benjamn/react-meteor)** [Meteor](http://www.meteor.com/) plugin.
|
||||
* **[pyReact](https://github.com/facebook/react-python)** [Python](http://www.python.org/) bridge to JSX.
|
||||
* **[react-rails](https://github.com/facebook/react-rails)** Ruby gem for using JSX with [Ruby on Rails](http://rubyonrails.org/).
|
||||
|
||||
### Full-stack starter kits
|
||||
|
||||
* **[react-quickstart](https://github.com/andreypopp/react-quickstart)** Quick-start template for `express`, `browserify`, `react-router-component` and `react-async` (**includes "isomorphic" server rendering**).
|
||||
* **[generator-react-webpack](https://github.com/newtriks/generator-react-webpack)** [Yeoman](http://yeoman.io/) generator for React and Webpack.
|
||||
* **[Genesis Skeleton](http://genesis-skeleton.com/)** Modern, opinionated, full-stack starter kit for rapid, streamlined application development (supports React).
|
||||
* **[react-starter-template](https://github.com/johnthethird/react-starter-template)** Starter template with Gulp, Webpack and Bootstrap.
|
||||
* **[react-brunch](https://npmjs.org/package/react-brunch)** [Brunch](http://brunch.io/) plugin.
|
||||
* **[react-browserify-template](https://github.com/petehunt/react-browserify-template)** Quick-start with Browserify.
|
||||
|
||||
### Routing
|
||||
|
||||
* **[director](https://github.com/flatiron/director)** (For an example see [TodoMVC](https://github.com/tastejs/todomvc/blob/gh-pages/architecture-examples/react/js/app.jsx#L29)).
|
||||
* **[Backbone](http://backbonejs.org/)** (For an example see [github-issues-viewer](https://github.com/jaredly/github-issues-viewer)).
|
||||
* **[react-router](https://github.com/jaredly/react-router)** (Example coming soon).
|
||||
* **[react-router-component](http://andreypopp.viewdocs.io/react-router-component)**
|
||||
|
||||
### Model management
|
||||
|
||||
* **[react.backbone](https://github.com/usepropeller/react.backbone)** Use [Backbone](http://backbonejs.org) models with React.
|
||||
* **[cortex](https://github.com/mquan/cortex/)** A JavaScript library for centrally managing data with React.
|
||||
* **[avers](https://github.com/wereHamster/avers)** A modern client-side model abstraction library.
|
||||
|
||||
### Data fetching
|
||||
|
||||
* **[react-async](http://andreypopp.viewdocs.io/react-async)** Adds a `getInitialStateAsync(cb)` method suitable for data fetching on both the client and the server.
|
||||
* **[superagent](http://visionmedia.github.io/superagent/)** A lightweight "isomorphic" library for AJAX requests.
|
||||
|
||||
### UI components
|
||||
|
||||
* **[react-bootstrap](https://github.com/stevoland/react-bootstrap)** Bootstrap 3 components built with React.
|
||||
* **[react-topcoat](https://github.com/plaxdan/react-topcoat)** Topcoat components built with React.
|
||||
* **[react-lorem-component](https://github.com/martinandert/react-lorem-component)** Lorem Ipsum placeholder component.
|
||||
* **[wingspan-forms](https://github.com/wingspan/wingspan-forms)** React library for dynamic forms & grids; widgets provided by KendoUI.
|
||||
* **[react-translate-component](https://github.com/martinandert/react-translate-component)** React component for i18n.
|
||||
This page has moved to the [GitHub wiki](https://github.com/facebook/react/wiki/Complementary-Tools).
|
||||
|
||||
97
docs/docs/flux-overview.md
Normal file
97
docs/docs/flux-overview.md
Normal file
@@ -0,0 +1,97 @@
|
||||
---
|
||||
id: flux-overview
|
||||
title: Flux Application Architecture
|
||||
layout: docs
|
||||
next: flux-todo-list.html
|
||||
---
|
||||
|
||||
Flux is the application architecture that Facebook uses for building client-side web applications. It complements React's composable view components by utilizing a unidirectional data flow. It's more of a pattern rather than a formal framework, and you can start using Flux immediately without a lot of new code.
|
||||
|
||||
<figure><iframe width="560" height="315" src="//www.youtube.com/embed/nYkdrAPrdcw?list=PLb0IAmt7-GS188xDYE-u1ShQmFFGbrk0v" frameborder="0" allowfullscreen></iframe></figure>
|
||||
|
||||
Flux applications have three major parts: the dispatcher, the stores, and the views (React components). These should not be confused with Model-View-Controller. Controllers do exist in a Flux application, but they are controller-views — views often found at the top of the hierarchy that retrieve data from the stores and pass this data down to their children. Additionally, actions — dispatcher helper methods — are often used to support a semantic dispatcher API. It can be useful to think of them as a fourth part of the Flux update cycle.
|
||||
|
||||
Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with a React view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all of the views that are affected. This works especially well with React's declarative programming style, which allows the store to send updates without specifying how to transition views between states.
|
||||
|
||||
We originally set out to deal correctly with derived data: for example, we wanted to show an unread count for message threads while another view showed a list of threads, with the unread ones highlighted. This was difficult to handle with MVC — marking a single thread as read would update the thread model, and then also need to update the unread count model. These dependencies and cascading updates often occur in a large MVC application, leading to a tangled weave of data flow and unpredictable results.
|
||||
|
||||
Control is inverted with stores: the stores accept updates and reconcile them as appropriate, rather than depending on something external to update its data in a consistent way. Nothing outside the store has any insight into how it manages the data for its domain, helping to keep a clear separation of concerns. This also makes stores more testable than models, especially since stores have no direct setter methods like `setAsRead()`, but instead have only an input point for the payload, which is delivered through the dispatcher and originates with actions.
|
||||
|
||||
|
||||
## Structure and Data Flow
|
||||
|
||||
Data in a Flux application flows in a single direction, in a cycle:
|
||||
|
||||
<pre>
|
||||
Views ---> (actions) ----> Dispatcher ---> (registered callback) ---> Stores -------+
|
||||
Ʌ |
|
||||
| V
|
||||
+-- (Controller-Views "change" event handlers) ---- (Stores emit "change" events) --+
|
||||
</pre>
|
||||
|
||||
A unidirectional data flow is central to the Flux pattern, and in fact Flux takes its name from the Latin word for flow. In the above diagram, the dispatcher, stores and views are independent nodes with distinct inputs and outputs. The actions are simply discrete, semantic helper functions that facilitate passing data to the dispatcher.
|
||||
|
||||
All data flows through the dispatcher as a central hub. Actions most often originate from user interactions with the views, and are nothing more than a call into the dispatcher. The dispatcher then invokes the callbacks that the stores have registered with it, effectively dispatching the data payload contained in the actions to all stores. Within their registered callbacks, stores determine which actions they are interested in, and respond accordingly. The stores then emit a "change" event to alert the controller-views that a change to the data layer has occurred. Controller-views listen for these events and retrieve data from the stores in an event handler. The controller-views call their own `render()` method via `setState()` or `forceUpdate()`, updating themselves and all of their children.
|
||||
|
||||
This structure allows us to reason easily about our application in a way that is reminiscent of functional reactive programming, or more specifically data-flow programming or flow-based programming, where data flows through the application in a single direction — there are no two-way bindings. Application state is maintained only in the stores, allowing the different parts of the application to remain highly decoupled. Where dependencies do occur between stores, they are kept in a strict hierarchy, with synchronous updates managed by the dispatcher.
|
||||
|
||||
We found that two-way data bindings led to cascading updates, where changing one object led to another object changing, which could also trigger more updates. As applications grew, these cascading updates made it very difficult to predict what would change as the result of one user interaction. When updates can only change data within a single round, the system as a whole becomes more predictable.
|
||||
|
||||
Let's look at the various parts of the Flux update cycle up close. A good place to start is the dispatcher.
|
||||
|
||||
|
||||
### A Single Dispatcher
|
||||
|
||||
The dispatcher is the central hub that manages all data flow in a Flux application. It is essentially a registry of callbacks into the stores. Each store registers itself and provides a callback. When the dispatcher responds to an action, all stores in the application are sent the data payload provided by the action via the callbacks in the registry.
|
||||
|
||||
As an application grows, the dispatcher becomes more vital, as it can manage dependencies between stores by invoking the registered callbacks in a specific order. Stores can declaratively wait for other stores to finish updating, and then update themselves accordingly.
|
||||
|
||||
|
||||
### Stores
|
||||
|
||||
Stores contain the application state and logic. Their role is somewhat similar to a model in a traditional MVC, but they manage the state of many objects — they are not instances of one object. Nor are they the same as Backbone's collections. More than simply managing a collection of ORM-style objects, stores manage the application state for a particular __domain__ within the application.
|
||||
|
||||
For example, Facebook's [Lookback Video Editor](https://facebook.com/lookback/edit) utilized a TimeStore that kept track of the playback time position and the playback state. On the other hand, the same application's ImageStore kept track of a collection of images. The TodoStore in our [TodoMVC example](https://github.com/facebook/react/tree/master/examples/todomvc-flux) is similar in that it manages a collection of to-do items. A store exhibits characteristics of both a collection of models and a singleton model of a logical domain.
|
||||
|
||||
As mentioned above, a store registers itself with the dispatcher and provides it with a callback. This callback receives the action's data payload as a parameter. The payload contains a type attribute, identifying the action's type. Within the store's registered callback, a switch statement based on the action's type is used to interpret the payload and to provide the proper hooks into the store's internal methods. This allows an action to result in an update to the state of the store, via the dispatcher. After the stores are updated, they broadcast an event declaring that their state has changed, so the views may query the new state and update themselves.
|
||||
|
||||
|
||||
### Views and Controller-Views
|
||||
|
||||
React provides the kind of composable views we need for the view layer. Close to the top of the nested view hierarchy, a special kind of view listens for events that are broadcast by the stores that it depends on. One could call this a controller-view, as it provides the glue code to get the data from the stores and to pass this data down the chain of its descendants. We might have one of these controller-views governing any significant section of the page.
|
||||
|
||||
When it receives the event from the store, it first requests the new data it needs via the stores' public getter methods. It then calls its own `setState()` or `forceUpdate()` methods, causing its `render()` method and the `render()` method of all its descendants to run.
|
||||
|
||||
We often pass the entire state of the store down the chain of views in a single object, allowing different descendants to use what they need. In addition to keeping the controller-like behavior at the top of the hierarchy, and thus keeping our descendant views as functionally pure as possible, passing down the entire state of the store in a single object also has the effect of reducing the number of props we need to manage.
|
||||
|
||||
Occasionally we may need to add additional controller-views deeper in the hierarchy to keep components simple. This might help us to better encapsulate a section of the hierarchy related to a specific data domain. Be aware, however, that controller-views deeper in the hierarchy can violate the singular flow of data by introducing a new, potentially conflicting entry point for the data flow. In making the decision of whether to add a deep controller-view, balance the gain of simpler components against the complexity of multiple data updates flowing into the hierarchy at different points. These multiple data updates can lead to odd effects, with React's render method getting invoked repeatedly by updates from different controller-views, potentially increasing the difficulty of debugging.
|
||||
|
||||
|
||||
### Actions
|
||||
|
||||
The dispatcher exposes a method that allows a view to trigger a dispatch to the stores, and to include a payload of data, or an action. The action construction may be wrapped into a semantic helper method which sends the payload to the dispatcher. For example, we may want to change the text of a to-do item in a to-do list application. We would create an action with a function signature like `updateText(todoId, newText)` in our `TodoActions` module. This method may be invoked from within our views' event handlers, so we can call it in response to a user action. This action method also adds the action type to the payload, so that when the payload is interpreted in the store, it can respond appropriately to a payload with a particular action type. In our example, this type might be named something like `TODO_UPDATE_TEXT`.
|
||||
|
||||
Actions may also come from other places, such as the server. This happens, for example, during data initialization. It may also happen when the server returns an error code or when the server has updates to provide to the application. We'll talk more about server actions in a future article. In this post we're only concerned with the basics of the data flow.
|
||||
|
||||
|
||||
### What About that Dispatcher?
|
||||
|
||||
As mentioned earlier, the dispatcher is also able to manage dependencies between stores. This functionality is available through the `waitFor()` method within the Dispatcher class. We did not need to use this method within the extremely simple [TodoMVC application](https://github.com/facebook/react/tree/master/examples/todomvc-flux), but we have included it [in the example dispatcher](https://github.com/facebook/react/blob/master/examples/todomvc-flux/js/dispatcher/Dispatcher.js#L110) as an example of what a dispatcher should be able to do in a larger, more complex application.
|
||||
|
||||
Within the TodoStore's registered callback we could explicitly wait for any dependencies to first update before moving forward:
|
||||
|
||||
```javascript
|
||||
case 'TODO_CREATE':
|
||||
Dispatcher.waitFor([
|
||||
PrependedTextStore.dispatcherIndex,
|
||||
YetAnotherStore.dispatcherIndex
|
||||
], function() {
|
||||
TodoStore.create(PrependedTextStore.getText() + ' ' + action.text);
|
||||
TodoStore.emit('change');
|
||||
});
|
||||
break;
|
||||
```
|
||||
|
||||
The arguments for `waitFor()` are an array of dipatcher registry indexes, and a final callback to invoke after the callbacks at the given indexes have completed. Thus the store that is invoking `waitFor()` can depend on the state of another store to inform how it should update its own state.
|
||||
|
||||
A problem arises if we create circular dependencies. If Store A waits for Store B, and B waits for A, then we'll have a very bad situation on our hands. We'll need a more robust dispatcher that flags these circular dependencies with console errors, and this is not easily accomplished with promises. Unfortunately, that's a bit beyond the scope of this documentation. In the future we hope to cover how to build a more robust dispatcher and how to initialize, update, and save the state of the application with persistent data, like a web service API.
|
||||
608
docs/docs/flux-todo-list.md
Normal file
608
docs/docs/flux-todo-list.md
Normal file
@@ -0,0 +1,608 @@
|
||||
---
|
||||
id: flux-todo-list
|
||||
title: Flux TodoMVC Tutorial
|
||||
layout: docs
|
||||
prev: flux-overview.html
|
||||
---
|
||||
|
||||
To demonstrate the Flux architecture with some example code, let's take on the classic TodoMVC application. The entire application is available in the React GitHub repo within the [todomvc-flux](https://github.com/facebook/react/tree/master/examples/todomvc-flux) example directory, but let's walk through the development of it a step at a time.
|
||||
|
||||
To begin, we'll need some boilerplate and get up and running with a module system. Node's module system, based on CommonJS, will fit the bill very nicely and we can build off of [react-boilerplate](https://github.com/petehunt/react-boilerplate) to get up and running quickly. Assuming you have npm installed, simply clone the react-boilerplate code from GitHub, and navigate into the resulting directory in Terminal (or whatever CLI application you like). Next run the npm scripts to get up and running: `npm install`, then `npm run build`, and lastly `npm start` to continuously build using Browserify.
|
||||
|
||||
The TodoMVC example has all this built into it as well, but if you're starting with react-boilerplate make sure you edit your package.json file to match the file structure and dependencies described in the TodoMVC example's [package.json](https://github.com/facebook/react/tree/master/examples/todomvc-flux/package.json), or else your code won't match up with the explanations below.
|
||||
|
||||
|
||||
Source Code Structure
|
||||
---------------------
|
||||
The resulting index.js file may be used as the entry point into our app, but we'll put most of our code in a 'js' directory. Let's let Browserify do its thing, and now we'll open a new tab in Terminal (or a GUI file browser) to look at the directory. It should look something like this:
|
||||
|
||||
```
|
||||
myapp
|
||||
|
|
||||
+ ...
|
||||
+ js
|
||||
|
|
||||
+ app.js
|
||||
+ bundle.js // generated by Browserify whenever we make changes.
|
||||
+ index.html
|
||||
+ ...
|
||||
```
|
||||
|
||||
Next we'll dive into the js directory, and layout our application's primary directory structure:
|
||||
|
||||
```
|
||||
myapp
|
||||
|
|
||||
+ ...
|
||||
+ js
|
||||
|
|
||||
+ actions
|
||||
+ components // all React components, both views and controller-views
|
||||
+ constants
|
||||
+ dispatcher
|
||||
+ stores
|
||||
+ app.js
|
||||
+ bundle.js
|
||||
+ index.html
|
||||
+ ...
|
||||
```
|
||||
|
||||
Creating a Dispatcher
|
||||
---------------------
|
||||
|
||||
Now we are ready to create a dispatcher. Here is an naive example of a Dispatcher class, written with JavaScript promises, polyfilled with Jake Archibald's [ES6-Promises](https://github.com/jakearchibald/ES6-Promises) module.
|
||||
|
||||
```javascript
|
||||
var Promise = require('es6-promise').Promise;
|
||||
var merge = require('react/lib/merge');
|
||||
|
||||
var _callbacks = [];
|
||||
var _promises = [];
|
||||
|
||||
/**
|
||||
* Add a promise to the queue of callback invocation promises.
|
||||
* @param {function} callback The Store's registered callback.
|
||||
* @param {object} payload The data from the Action.
|
||||
*/
|
||||
var _addPromise = function(callback, payload) {
|
||||
_promises.push(new Promise(function(resolve, reject) {
|
||||
if (callback(payload)) {
|
||||
resolve(payload);
|
||||
} else {
|
||||
reject(new Error('Dispatcher callback unsuccessful'));
|
||||
}
|
||||
}));
|
||||
};
|
||||
|
||||
/**
|
||||
* Empty the queue of callback invocation promises.
|
||||
*/
|
||||
var _clearPromises = function() {
|
||||
_promises = [];
|
||||
};
|
||||
|
||||
var Dispatcher = function() {};
|
||||
Dispatcher.prototype = merge(Dispatcher.prototype, {
|
||||
|
||||
/**
|
||||
* Register a Store's callback so that it may be invoked by an action.
|
||||
* @param {function} callback The callback to be registered.
|
||||
* @return {number} The index of the callback within the _callbacks array.
|
||||
*/
|
||||
register: function(callback) {
|
||||
_callbacks.push(callback);
|
||||
return _callbacks.length - 1; // index
|
||||
},
|
||||
|
||||
/**
|
||||
* dispatch
|
||||
* @param {object} payload The data from the action.
|
||||
*/
|
||||
dispatch: function(payload) {
|
||||
_callbacks.forEach(function(callback) {
|
||||
_addPromise(callback, payload);
|
||||
});
|
||||
Promise.all(_promises).then(_clearPromises);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = Dispatcher;
|
||||
```
|
||||
|
||||
The public API of this basic Dispatcher consists of only two methods: register() and dispatch(). We'll use register() within our stores to register each store's callback. We'll use dispatch() within our actions to trigger the invocation of the callbacks.
|
||||
|
||||
Now we are all set to create a dispatcher that is more specific to our app, which we'll call AppDispatcher.
|
||||
|
||||
```javascript
|
||||
var Dispatcher = require('./Dispatcher');
|
||||
|
||||
var merge = require('react/lib/merge');
|
||||
|
||||
var AppDispatcher = merge(Dispatcher.prototype, {
|
||||
|
||||
/**
|
||||
* A bridge function between the views and the dispatcher, marking the action
|
||||
* as a view action. Another variant here could be handleServerAction.
|
||||
* @param {object} action The data coming from the view.
|
||||
*/
|
||||
handleViewAction: function(action) {
|
||||
this.dispatch({
|
||||
source: 'VIEW_ACTION',
|
||||
action: action
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = AppDispatcher;
|
||||
```
|
||||
|
||||
Now we've created an implementation that is a bit more specific to our needs, with a helper function we can use in the actions coming from our views' event handlers. We might expand on this later to provide a separate helper for server updates, but for now this is all we need.
|
||||
|
||||
|
||||
Creating Stores
|
||||
----------------
|
||||
|
||||
We can use Node's EventEmitter to get started with a store. We need EventEmitter to broadcast the 'change' event to our controller-views. So let's take a look at what that looks like. I've omitted some of the code for the sake of brevity, but for the full version see [TodoStore.js](https://github.com/Facebook/react/blob/master/examples/todomvc-flux/js/stores/TodoStore.js) in the TodoMVC example code.
|
||||
|
||||
```javascript
|
||||
var AppDispatcher = require('../dispatcher/AppDispatcher');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var TodoConstants = require('../constants/TodoConstants');
|
||||
var merge = require('react/lib/merge');
|
||||
|
||||
var CHANGE_EVENT = 'change';
|
||||
|
||||
var _todos = {}; // collection of todo items
|
||||
|
||||
/**
|
||||
* Create a TODO item.
|
||||
* @param {string} text The content of the TODO
|
||||
*/
|
||||
function create(text) {
|
||||
// Using the current timestamp in place of a real id.
|
||||
var id = Date.now();
|
||||
_todos[id] = {
|
||||
id: id,
|
||||
complete: false,
|
||||
text: text
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a TODO item.
|
||||
* @param {string} id
|
||||
*/
|
||||
function destroy(id) {
|
||||
delete _todos[id];
|
||||
}
|
||||
|
||||
var TodoStore = merge(EventEmitter.prototype, {
|
||||
|
||||
/**
|
||||
* Get the entire collection of TODOs.
|
||||
* @return {object}
|
||||
*/
|
||||
getAll: function() {
|
||||
return _todos;
|
||||
},
|
||||
|
||||
emitChange: function() {
|
||||
this.emit(CHANGE_EVENT);
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {function} callback
|
||||
*/
|
||||
addChangeListener: function(callback) {
|
||||
this.on(CHANGE_EVENT, callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {function} callback
|
||||
*/
|
||||
removeChangeListener: function(callback) {
|
||||
this.removeListener(CHANGE_EVENT, callback);
|
||||
}
|
||||
|
||||
dispatcherIndex: AppDispatcher.register(function(payload) {
|
||||
var action = payload.action;
|
||||
var text;
|
||||
|
||||
switch(action.actionType) {
|
||||
case TodoConstants.TODO_CREATE:
|
||||
text = action.text.trim();
|
||||
if (text !== '') {
|
||||
create(text);
|
||||
TodoStore.emitChange();
|
||||
}
|
||||
break;
|
||||
|
||||
case TodoConstants.TODO_DESTROY:
|
||||
destroy(action.id);
|
||||
TodoStore.emitChange();
|
||||
break;
|
||||
|
||||
// add more cases for other actionTypes, like TODO_UPDATE, etc.
|
||||
}
|
||||
|
||||
return true; // No errors. Needed by promise in Dispatcher.
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
module.exports = TodoStore;
|
||||
```
|
||||
|
||||
There are a few important things to note in the above code. To start, we are maintaining a private data structure called _todos. This object contains all the individual to-do items. Because this variable lives outside the class, but within the closure of the module, it remains private — it cannot be directly changed from the outside. This helps us preserve a distinct input/output interface for the flow of data by making it impossible to update the store without using an action.
|
||||
|
||||
Another important part is the registration of the store's callback with the dispatcher. We pass in our payload handling callback to the dispatcher and preserve the index that this store has in the dispatcher's registry. The callback function currently only handles one actionType, but later we can add as many as we need.
|
||||
|
||||
|
||||
Listening to Changes with a Controller-View
|
||||
-------------------------------------------
|
||||
|
||||
We need a React component near the top of our component hierarchy to listen for changes in the store. In a larger app, we would have more of these listening components, perhaps one for every section of the page. In Facebook's Ads Creation Tool, we have many of these controller-like views, each governing a specific section of the UI. In the Lookback Video Editor, we only had two: one for the animated preview and one for the image selection interface. Here's one for our TodoMVC example. Again, this is slightly abbreviated, but for the full code you can take a look at the TodoMVC example's [TodoApp.react.js](https://github.com/facebook/react/blob/master/examples/todomvc-flux/js/components/TodoApp.react.js)
|
||||
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var Footer = require('./Footer.react');
|
||||
var Header = require('./Header.react');
|
||||
var MainSection = require('./MainSection.react');
|
||||
var React = require('react');
|
||||
var TodoStore = require('../stores/TodoStore');
|
||||
|
||||
function getTodoState() {
|
||||
return {
|
||||
allTodos: TodoStore.getAll()
|
||||
};
|
||||
}
|
||||
|
||||
var TodoApp = React.createClass({
|
||||
|
||||
getInitialState: function() {
|
||||
return getTodoState();
|
||||
},
|
||||
|
||||
componentDidMount: function() {
|
||||
TodoStore.addChangeListener(this._onChange);
|
||||
},
|
||||
|
||||
componentWillUnmount: function() {
|
||||
TodoStore.removeChangeListener(this._onChange);
|
||||
},
|
||||
|
||||
/**
|
||||
* @return {object}
|
||||
*/
|
||||
render: function() {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
<MainSection
|
||||
allTodos={this.state.allTodos}
|
||||
areAllComplete={this.state.areAllComplete}
|
||||
/>
|
||||
<Footer allTodos={this.state.allTodos} />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
|
||||
_onChange: function() {
|
||||
this.setState(getTodoState());
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = TodoApp;
|
||||
```
|
||||
|
||||
Now we're in our familiar React territory, utilizing React's lifecycle methods. We set up the initial state of this controller-view in getInitialState(), register an event listener in componentDidMount(), and then clean up after ourselves within componentWillUnmount(). We render a containing div and pass down the collection of states we got from the TodoStore.
|
||||
|
||||
The Header component contains the primary text input for the application, but it does not need to know the state of the store. The MainSection and Footer do need this data, so we pass it down to them.
|
||||
|
||||
More Views
|
||||
----------
|
||||
At a high level, the React component hierarchy of the app looks like this:
|
||||
|
||||
```javascript
|
||||
<TodoApp>
|
||||
<Header>
|
||||
<TodoTextInput />
|
||||
|
||||
<MainSection>
|
||||
<ul>
|
||||
<TodoItem />
|
||||
</ul>
|
||||
</MainSection>
|
||||
|
||||
</TodoApp>
|
||||
```
|
||||
If a TodoItem is in edit mode, it will also render a TodoTextInput as a child. Let's take a look at how some of these components display the data they receive as props, and how they communicate through actions with the dispatcher.
|
||||
The MainSection needs to iterate over the collection of to-do items it received from TodoApp to create the list of TodoItems. In the component's render() method, we can do that iteration like so:
|
||||
|
||||
```javascript
|
||||
var allTodos = this.props.allTodos;
|
||||
|
||||
for (var key in allTodos) {
|
||||
todos.push(<TodoItem key={key} todo={allTodos[key]} />);
|
||||
}
|
||||
|
||||
return (
|
||||
<section id="main">
|
||||
<ul id="todo-list">{todos}</ul>
|
||||
);
|
||||
```
|
||||
Now each TodoItem can display it's own text, and perform actions utilizing it's own ID. Explaining all the different actions that a TodoItem can invoke in the TodoMVC example goes beyond the scope of this article, but let's just take a look at the action that deletes one of the to-do items. Here is an abbreviated version of the TodoItem:
|
||||
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var React = require('react');
|
||||
var TodoActions = require('../actions/TodoActions');
|
||||
var TodoTextInput = require('./TodoTextInput.react');
|
||||
|
||||
var TodoItem = React.createClass({
|
||||
|
||||
propTypes: {
|
||||
todo: React.PropTypes.object.isRequired
|
||||
},
|
||||
|
||||
render: function() {
|
||||
var todo = this.props.todo;
|
||||
|
||||
return (
|
||||
<li
|
||||
key={todo.id}>
|
||||
<label>
|
||||
{todo.text}
|
||||
</label>
|
||||
<button className="destroy" onClick={this._onDestroyClick} />
|
||||
</li>
|
||||
);
|
||||
},
|
||||
|
||||
_onDestroyClick: function() {
|
||||
TodoActions.destroy(this.props.todo.id);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = TodoItem;
|
||||
```
|
||||
|
||||
With a destroy action available in our library of TodoActions, and a store ready to handle it, connecting the user's interaction with application state changes could not be simpler. We just wrap our onClick handler around the destroy action, provide it with the id, and we're done. Now the user can click the destroy button and kick off the Flux cycle to update the rest of the application.
|
||||
|
||||
Text input, on the other hand, is just a bit more complicated because we need to hang on to the state of the text input within the React component itself. Let's take a look at how TodoTextInput works.
|
||||
|
||||
As you'll see below, with every change to the input, React expects us to update the state of the component. So when we are finally ready to save the text inside the input, we will put the value held in the component's state in the action's payload. This is UI state, rather than application state, and keeping that distinction in mind is a good guide for where state should live. All application state should live in the store, while components occasionally hold on to UI state. Ideally, React components preserve as little state as possible.
|
||||
|
||||
Because TodoTextInput is being used in multiple places within our application, with different behaviors, we'll need to pass the onSave method in as a prop from the component's parent. This allows onSave to invoke different actions depending on where it is used.
|
||||
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var React = require('react');
|
||||
var ReactPropTypes = React.PropTypes;
|
||||
|
||||
var ENTER_KEY_CODE = 13;
|
||||
|
||||
var TodoTextInput = React.createClass({
|
||||
|
||||
propTypes: {
|
||||
className: ReactPropTypes.string,
|
||||
id: ReactPropTypes.string,
|
||||
placeholder: ReactPropTypes.string,
|
||||
onSave: ReactPropTypes.func.isRequired,
|
||||
value: ReactPropTypes.string
|
||||
},
|
||||
|
||||
getInitialState: function() {
|
||||
return {
|
||||
value: this.props.value || ''
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* @return {object}
|
||||
*/
|
||||
render: function() /*object*/ {
|
||||
return (
|
||||
<input
|
||||
className={this.props.className}
|
||||
id={this.props.id}
|
||||
placeholder={this.props.placeholder}
|
||||
onBlur={this._save}
|
||||
onChange={this._onChange}
|
||||
onKeyDown={this._onKeyDown}
|
||||
value={this.state.value}
|
||||
autoFocus={true}
|
||||
/>
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Invokes the callback passed in as onSave, allowing this component to be
|
||||
* used in different ways.
|
||||
*/
|
||||
_save: function() {
|
||||
this.props.onSave(this.state.value);
|
||||
this.setState({
|
||||
value: ''
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {object} event
|
||||
*/
|
||||
_onChange: function(/*object*/ event) {
|
||||
this.setState({
|
||||
value: event.target.value
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {object} event
|
||||
*/
|
||||
|
||||
_onKeyDown: function(event) {
|
||||
if (event.keyCode === ENTER_KEY_CODE) {
|
||||
this._save();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = TodoTextInput;
|
||||
```
|
||||
|
||||
The Header passes in the onSave method as a prop to allow the TodoTextInput to create new
|
||||
to-do items:
|
||||
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var React = require('react');
|
||||
var TodoActions = require('../actions/TodoActions');
|
||||
var TodoTextInput = require('./TodoTextInput.react');
|
||||
|
||||
var Header = React.createClass({
|
||||
|
||||
/**
|
||||
* @return {object}
|
||||
*/
|
||||
render: function() {
|
||||
return (
|
||||
<header id="header">
|
||||
<h1>todos</h1>
|
||||
<TodoTextInput
|
||||
id="new-todo"
|
||||
placeholder="What needs to be done?"
|
||||
onSave={this._onSave}
|
||||
/>
|
||||
</header>
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Event handler called within TodoTextInput.
|
||||
* Defining this here allows TodoTextInput to be used in multiple places
|
||||
* in different ways.
|
||||
* @param {string} text
|
||||
*/
|
||||
_onSave: function(text) {
|
||||
TodoActions.create(text);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = Header;
|
||||
```
|
||||
|
||||
In a different context, such as in editing mode for an existing to-do item, we might pass an onSave callback that invokes `TodoActions.update(text)` instead.
|
||||
|
||||
|
||||
Creating Semantic Actions
|
||||
-------------------------
|
||||
|
||||
Here is the basic code for the two actions we used above in our views:
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* TodoActions
|
||||
*/
|
||||
|
||||
var AppDispatcher = require('../dispatcher/AppDispatcher');
|
||||
var TodoConstants = require('../constants/TodoConstants');
|
||||
|
||||
var TodoActions = {
|
||||
|
||||
/**
|
||||
* @param {string} text
|
||||
*/
|
||||
create: function(text) {
|
||||
AppDispatcher.handleViewAction({
|
||||
actionType: TodoConstants.TODO_CREATE,
|
||||
text: text
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
*/
|
||||
destroy: function(id) {
|
||||
AppDispatcher.handleViewAction({
|
||||
actionType: TodoConstants.TODO_DESTROY,
|
||||
id: id
|
||||
});
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
module.exports = TodoActions;
|
||||
```
|
||||
|
||||
As you can see, we really would not need to have the helpers AppDispatcher.handleViewAction() or TodoActions.create(). We could, in theory, call AppDispatcher.dispatch() directly and provide a payload. But as our application grows, having these helpers keeps the code clean and semantic. It's just a lot cleaner to write TodoActions.destroy(id) instead of writing a whole lot of things that our TodoItem shouldn't have to know about.
|
||||
|
||||
The payload produced by the TodoActions.create() will look like:
|
||||
|
||||
```javascript
|
||||
{
|
||||
source: 'VIEW_ACTION',
|
||||
action: {
|
||||
type: 'TODO_CREATE',
|
||||
text: 'Write blog post about Flux'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This payload is provided to the TodoStore through its registered callback. The TodoStore then broadcasts the 'change' event, and the MainSection responds by fetching the new collection of to-do items from the TodoStore and changing its state. This change in state causes the TodoApp component to call its own render() method, and the render() method of all of its descendents.
|
||||
|
||||
Start Me Up
|
||||
-----------
|
||||
|
||||
The bootstrap file of our application is app.js. It simply takes the TodoApp component and renders it in the root element of the application.
|
||||
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var React = require('react');
|
||||
|
||||
var TodoApp = require('./components/TodoApp.react');
|
||||
|
||||
React.renderComponent(
|
||||
<TodoApp />,
|
||||
document.getElementById('todoapp')
|
||||
);
|
||||
```
|
||||
|
||||
Adding Dependency Management to the Dispatcher
|
||||
----------------------------------------------
|
||||
|
||||
As I said previously, our Dispatcher implementation is a bit naive. It's pretty good, but it will not suffice for most applications. We need a way to be able to manage dependencies between Stores. Let's add that functionality with a waitFor() method within the main body of the Dispatcher class.
|
||||
|
||||
We'll need another public method, waitFor().
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* @param {array} promisesIndexes
|
||||
* @param {function} callback
|
||||
*/
|
||||
waitFor: function(promiseIndexes, callback) {
|
||||
var selectedPromises = _promises.filter(function(/*object*/ _, /*number*/ j) {
|
||||
return promiseIndexes.indexOf(j) !== -1;
|
||||
});
|
||||
Promise.all(selectedPromises).then(callback);
|
||||
}
|
||||
```
|
||||
|
||||
Now within the TodoStore callback we can explicitly wait for any dependencies to first update before moving forward. However, if Store A waits for Store B, and B waits for A, then a circular dependency will occur. A more robust dispatcher is required to flag this scenario with warnings in the console.
|
||||
|
||||
The Future of Flux
|
||||
------------------
|
||||
|
||||
A lot of people ask if Facebook will release Flux as an open source framework. Really, Flux is just an architecture, not a framework. But perhaps a Flux boilerplate project might make sense, if there is enough interest. Please let us know if you'd like to see us do this.
|
||||
|
||||
Thanks for taking the time to read about how we build client-side applications at Facebook. We hope Flux proves as useful to you as it has to us.
|
||||
@@ -9,7 +9,7 @@ next: component-specs.html
|
||||
|
||||
## ReactComponent
|
||||
|
||||
Component classes created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
|
||||
Component classes created by `React.createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
|
||||
|
||||
|
||||
### getDOMNode
|
||||
@@ -24,20 +24,24 @@ If this component has been mounted into the DOM, this returns the corresponding
|
||||
### setProps
|
||||
|
||||
```javascript
|
||||
setProps(object nextProps)
|
||||
setProps(object nextProps[, function callback])
|
||||
```
|
||||
|
||||
When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with `renderComponent()`. Simply call `setProps()` to change its properties and trigger a re-render.
|
||||
When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with `React.renderComponent()`.
|
||||
|
||||
Though calling `React.renderComponent()` again on the same node is the preferred way to update a root-level component, you can also call `setProps()` to change its properties and trigger a re-render. In addition, you can supply an optional callback function that is executed once `setProps` is completed and the component is re-rendered.
|
||||
|
||||
> 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()`.
|
||||
> When possible, the declarative approach of calling `React.renderComponent()` again is preferred; it tends to make updates easier to reason about. (There's no significant performance difference between the two approaches.)
|
||||
>
|
||||
> This method can only be called on a root-level component. That is, it's only available on the component passed directly to `React.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
|
||||
|
||||
```javascript
|
||||
replaceProps(object nextProps)
|
||||
replaceProps(object nextProps[, function callback])
|
||||
```
|
||||
|
||||
Like `setProps()` but deletes any pre-existing props instead of merging the two objects.
|
||||
@@ -76,7 +80,7 @@ Properties that are specified directly on the target component instance (such as
|
||||
setState(object nextState[, function callback])
|
||||
```
|
||||
|
||||
Merges nextState with the current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks. In addition, you can supply an optional callback function that is executed once `setState` is completed.
|
||||
Merges nextState with the current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks. In addition, you can supply an optional callback function that is executed once `setState` is completed and the component is re-rendered.
|
||||
|
||||
> Notes:
|
||||
>
|
||||
|
||||
@@ -61,7 +61,7 @@ Now that we've identified the components in our mock, let's arrange them into a
|
||||
|
||||
## Step 2: Build a static version in React
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/6wQMG/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/n25pd/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
|
||||
Now that you have your component hierarchy it's time to start implementing your app. The easiest way is to build a version that takes your data model and renders the UI but has no interactivity. It's easiest to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing. We'll see why.
|
||||
|
||||
@@ -105,7 +105,7 @@ So finally, our state is:
|
||||
|
||||
## Step 4: Identify where your state should live
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/QvHnx/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/t53sx/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
|
||||
OK, so we've identified what the minimal set of app state is. Next we need to identify which component mutates, or *owns*, this state.
|
||||
|
||||
@@ -130,7 +130,7 @@ You can start seeing how your application will behave: set `filterText` to `"bal
|
||||
|
||||
## Step 5: Add inverse data flow
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/3Vs3Q/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/F8H7p/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
|
||||
So far we've built an app that renders correctly as a function of props and state flowing down the hierarchy. Now it's time to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ It'll also have a few neat features:
|
||||
|
||||
### Want to skip all this and just see the source?
|
||||
|
||||
[It's all on GitHub.](https://github.com/petehunt/react-tutorial)
|
||||
[It's all on GitHub.](https://github.com/reactjs/react-tutorial)
|
||||
|
||||
### Getting started
|
||||
|
||||
@@ -40,9 +40,7 @@ For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your fav
|
||||
<body>
|
||||
<div id="content"></div>
|
||||
<script type="text/jsx">
|
||||
/**
|
||||
* @jsx React.DOM
|
||||
*/
|
||||
/** @jsx React.DOM */
|
||||
// The above declaration must remain intact at the top of the script.
|
||||
// Your code here
|
||||
</script>
|
||||
@@ -91,10 +89,9 @@ The first thing you'll notice is the XML-ish syntax in your JavaScript. We have
|
||||
var CommentBox = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
React.DOM.div({
|
||||
className: 'commentBox',
|
||||
children: 'Hello, world! I am a CommentBox.'
|
||||
})
|
||||
React.DOM.div({className: "commentBox"},
|
||||
"Hello, world! I am a CommentBox."
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -304,12 +301,16 @@ React.renderComponent(
|
||||
|
||||
Now that the data is available in the `CommentList`, let's render the comments dynamically:
|
||||
|
||||
```javascript{4-6,9}
|
||||
```javascript{4-10,13}
|
||||
// tutorial10.js
|
||||
var CommentList = React.createClass({
|
||||
render: function() {
|
||||
var commentNodes = this.props.data.map(function (comment) {
|
||||
return <Comment author={comment.author}>{comment.text}</Comment>;
|
||||
return (
|
||||
<Comment author={comment.author}>
|
||||
{comment.text}
|
||||
</Comment>
|
||||
);
|
||||
});
|
||||
return (
|
||||
<div className="commentList">
|
||||
@@ -411,7 +412,7 @@ var CommentBox = React.createClass({
|
||||
|
||||
Here, `componentWillMount` is a method called automatically by React before a component is rendered. The key to dynamic updates is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is only a minor change to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
|
||||
|
||||
```javascript{3,16-17,31}
|
||||
```javascript{3,19-20,34}
|
||||
// tutorial14.js
|
||||
var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
@@ -420,6 +421,9 @@ var CommentBox = React.createClass({
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this),
|
||||
error: function(xhr, status, err) {
|
||||
console.error(this.props.url, status, err.toString());
|
||||
}.bind(this)
|
||||
});
|
||||
},
|
||||
@@ -471,7 +475,7 @@ var CommentForm = React.createClass({
|
||||
|
||||
Let's make the form interactive. When the user submits the form, we should clear it, submit a request to the server, and refresh the list of comments. To start, let's listen for the form's submit event and clear it.
|
||||
|
||||
```javascript{3-13,16-17,21}
|
||||
```javascript{3-13,16-18}
|
||||
// tutorial16.js
|
||||
var CommentForm = React.createClass({
|
||||
handleSubmit: function() {
|
||||
@@ -489,11 +493,7 @@ var CommentForm = React.createClass({
|
||||
return (
|
||||
<form className="commentForm" onSubmit={this.handleSubmit}>
|
||||
<input type="text" placeholder="Your name" ref="author" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Say something..."
|
||||
ref="text"
|
||||
/>
|
||||
<input type="text" placeholder="Say something..." ref="text" />
|
||||
<input type="submit" value="Post" />
|
||||
</form>
|
||||
);
|
||||
@@ -517,7 +517,7 @@ When a user submits a comment, we will need to refresh the list of comments to i
|
||||
|
||||
We need to pass data from the child component to its parent. We do this by passing a `callback` in props from parent to child:
|
||||
|
||||
```javascript{12-14,28}
|
||||
```javascript{15-17,30}
|
||||
// tutorial17.js
|
||||
var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
@@ -526,6 +526,9 @@ var CommentBox = React.createClass({
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this),
|
||||
error: function(xhr, status, err) {
|
||||
console.error(this.props.url, status, err.toString());
|
||||
}.bind(this)
|
||||
});
|
||||
},
|
||||
@@ -544,9 +547,7 @@ var CommentBox = React.createClass({
|
||||
<div className="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
onCommentSubmit={this.handleCommentSubmit}
|
||||
/>
|
||||
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -570,11 +571,7 @@ var CommentForm = React.createClass({
|
||||
return (
|
||||
<form className="commentForm" onSubmit={this.handleSubmit}>
|
||||
<input type="text" placeholder="Your name" ref="author" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Say something..."
|
||||
ref="text"
|
||||
/>
|
||||
<input type="text" placeholder="Say something..." ref="text" />
|
||||
<input type="submit" value="Post" />
|
||||
</form>
|
||||
);
|
||||
@@ -584,7 +581,7 @@ var CommentForm = React.createClass({
|
||||
|
||||
Now that the callbacks are in place, all we have to do is submit to the server and refresh the list:
|
||||
|
||||
```javascript{13-21}
|
||||
```javascript{16-27}
|
||||
// tutorial19.js
|
||||
var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
@@ -593,6 +590,9 @@ var CommentBox = React.createClass({
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this),
|
||||
error: function(xhr, status, err) {
|
||||
console.error(this.props.url, status, err.toString());
|
||||
}.bind(this)
|
||||
});
|
||||
},
|
||||
@@ -604,6 +604,9 @@ var CommentBox = React.createClass({
|
||||
data: comment,
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this),
|
||||
error: function(xhr, status, err) {
|
||||
console.error(this.props.url, status, err.toString());
|
||||
}.bind(this)
|
||||
});
|
||||
},
|
||||
@@ -619,9 +622,7 @@ var CommentBox = React.createClass({
|
||||
<div className="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
onCommentSubmit={this.handleCommentSubmit}
|
||||
/>
|
||||
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -632,7 +633,7 @@ var CommentBox = React.createClass({
|
||||
|
||||
Our application is now feature complete but it feels slow to have to wait for the request to complete before your comment appears in the list. We can optimistically add this comment to the list to make the app feel faster.
|
||||
|
||||
```javascript{13-15}
|
||||
```javascript{16-18}
|
||||
// tutorial20.js
|
||||
var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
@@ -641,6 +642,9 @@ var CommentBox = React.createClass({
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this),
|
||||
error: function(xhr, status, err) {
|
||||
console.error(this.props.url, status, err.toString());
|
||||
}.bind(this)
|
||||
});
|
||||
},
|
||||
@@ -655,6 +659,9 @@ var CommentBox = React.createClass({
|
||||
data: comment,
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this),
|
||||
error: function(xhr, status, err) {
|
||||
console.error(this.props.url, status, err.toString());
|
||||
}.bind(this)
|
||||
});
|
||||
},
|
||||
@@ -670,9 +677,7 @@ var CommentBox = React.createClass({
|
||||
<div className="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
onCommentSubmit={this.handleCommentSubmit}
|
||||
/>
|
||||
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,18 @@ next: complementary-tools.html
|
||||
"At Facebook and Instagram, we’re trying to push the limits of what’s possible on the web with React. My talk will start with a brief introduction to the framework, and then dive into three controversial topics: Throwing out the notion of templates and building views with JavaScript, “re-rendering” your entire application when your data changes, and a lightweight implementation of the DOM and events." -- [Pete Hunt](http://www.petehunt.net/)
|
||||
|
||||
|
||||
### Thinking in react - tagtree.tv
|
||||
|
||||
A [tagtree.tv](http://tagtree.tv/) video conveying the principles of [Thinking in React](/react/docs/thinking-in-react.html) while building a simple app
|
||||
<figure>[](http://tagtree.tv/thinking-in-react)</figure>
|
||||
|
||||
|
||||
### Secrets of the Virtual DOM - MtnWest JS
|
||||
|
||||
<iframe width="560" height="315" src="//www.youtube.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
"In this talk I’ll be discussing why we built a virtual DOM, how it compares to other systems, and its relevance to the future of browser technologies." -- [Pete Hunt](http://www.petehunt.net/)
|
||||
|
||||
### CodeWinds
|
||||
|
||||
[Pete Hunt](http://www.petehunt.net/) talked with [Jeff Barczewski](http://jeff.barczewski.com/) about React in CodeWinds Episode 4.
|
||||
@@ -99,3 +111,7 @@ by [Stoyan Stefanov](http://www.phpied.com/)
|
||||
### "Functional DOM programming" - Meteor DevShop 11
|
||||
|
||||
<iframe width="650" height="315" src="//www.youtube.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
### "Rethinking Web App Development at Facebook" - Facebook F8 Conference 2014
|
||||
|
||||
<iframe width="650" height="315" src="//www.youtube.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
BIN
docs/downloads/react-0.10.0.zip
Normal file
BIN
docs/downloads/react-0.10.0.zip
Normal file
Binary file not shown.
BIN
docs/downloads/react-0.11.0-rc1.zip
Normal file
BIN
docs/downloads/react-0.11.0-rc1.zip
Normal file
Binary file not shown.
BIN
docs/img/docs/thinking-in-react-tagtree.png
Normal file
BIN
docs/img/docs/thinking-in-react-tagtree.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -20,5 +20,5 @@ React.renderComponent(<input value="hi" />, mountNode);
|
||||
|
||||
setTimeout(function() {
|
||||
React.renderComponent(<input value={null} />, mountNode);
|
||||
}, 2000);
|
||||
}, 1000);
|
||||
```
|
||||
|
||||
@@ -26,7 +26,7 @@ var UserGist = React.createClass({
|
||||
$.get(this.props.source, function(result) {
|
||||
var lastGist = result[0];
|
||||
this.setState({
|
||||
username: lastGist.user.login,
|
||||
username: lastGist.owner.login,
|
||||
lastGistUrl: lastGist.html_url
|
||||
});
|
||||
}.bind(this));
|
||||
|
||||
@@ -5,7 +5,7 @@ module.exports = {
|
||||
react_docs: {
|
||||
files: [
|
||||
{
|
||||
src: ['react.min.js', 'JSXTransformer.js'],
|
||||
src: ['react.js', 'JSXTransformer.js'],
|
||||
dest: 'docs/js/',
|
||||
cwd: 'build/',
|
||||
expand: true
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "react",
|
||||
"description": "React is a JavaScript library for building user interfaces.",
|
||||
"version": "0.10.0-rc1",
|
||||
"version": "0.10.0",
|
||||
"keywords": [
|
||||
"react"
|
||||
],
|
||||
|
||||
2000
npm-shrinkwrap.json
generated
Normal file
2000
npm-shrinkwrap.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "react-tools",
|
||||
"description": "A set of complementary tools to React, including the JSX transformer.",
|
||||
"version": "0.10.0-rc1",
|
||||
"version": "0.10.0",
|
||||
"keywords": [
|
||||
"react",
|
||||
"jsx",
|
||||
|
||||
@@ -92,6 +92,6 @@ if (__DEV__) {
|
||||
|
||||
// Version exists only in the open-source version of React, not in Facebook's
|
||||
// internal version.
|
||||
React.version = '0.10.0-rc1';
|
||||
React.version = '0.10.0';
|
||||
|
||||
module.exports = React;
|
||||
|
||||
Reference in New Issue
Block a user