Compare commits
56 Commits
v0.5.2
...
0.4-stable
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
283f4a8b04 | ||
|
|
393a889aac | ||
|
|
3e455a4397 | ||
|
|
91b2ac57d4 | ||
|
|
c8996773ae | ||
|
|
a2a7536f38 | ||
|
|
ce478822e8 | ||
|
|
b88f97f9be | ||
|
|
ddbf91afd1 | ||
|
|
ae95674173 | ||
|
|
9e11fb626e | ||
|
|
ec746d3a1b | ||
|
|
91976ea8b4 | ||
|
|
9040c5f3a8 | ||
|
|
08d72df56b | ||
|
|
d6edc1189a | ||
|
|
6f532a839f | ||
|
|
34589c0e0d | ||
|
|
d91b238015 | ||
|
|
db904c2597 | ||
|
|
c12929700a | ||
|
|
30a11d2d7e | ||
|
|
a5115a2489 | ||
|
|
8b1990caa7 | ||
|
|
007d8b4f79 | ||
|
|
e6b5013a8b | ||
|
|
e4fa9ca9ee | ||
|
|
176ef3521c | ||
|
|
58635eea36 | ||
|
|
f8737dc8fe | ||
|
|
01297cf212 | ||
|
|
89437e6a97 | ||
|
|
ed755945a3 | ||
|
|
018e08cdd8 | ||
|
|
949c69fd56 | ||
|
|
a244928353 | ||
|
|
c034435052 | ||
|
|
8795a78ca0 | ||
|
|
123d091cc0 | ||
|
|
764ca84e02 | ||
|
|
3d78d30f49 | ||
|
|
fae1c48470 | ||
|
|
9801937715 | ||
|
|
0cac12d375 | ||
|
|
1e2d37f7e8 | ||
|
|
38bce710ac | ||
|
|
374c3b8a29 | ||
|
|
c362c16e1e | ||
|
|
fa5da5c848 | ||
|
|
734ee22a0c | ||
|
|
84dbb9bcd1 | ||
|
|
8ed80cae94 | ||
|
|
8b995ceb6a | ||
|
|
2e3594c8bc | ||
|
|
b2b9c690f8 | ||
|
|
7a760a5135 |
21
.mailmap
@@ -1,21 +0,0 @@
|
||||
Ben Newman <bn@cs.stanford.edu> <benjamn@fb.com>
|
||||
Dan Schafer <dschafer@fb.com>
|
||||
Harry Hull <harry.hull1@gmail.com>
|
||||
Jeff Morrison <jeff@anafx.com> <Jeff@anafx.com>
|
||||
Jeff Morrison <jeff@anafx.com> JeffMo <jeffmo@fb.com>
|
||||
Jeffrey Lin <lin.jeffrey@gmail.com> <jeffreylin@fb.com>
|
||||
Jordan Walke <jordojw@gmail.com>
|
||||
Jordan Walke <jordojw@gmail.com> <jordanjcw@fb.com>
|
||||
Laurence Rowe <l@lrowe.co.uk> <laurence@lrowe.co.uk>
|
||||
Nick Gavalas <njg57@cornell.edu>
|
||||
Paul O’Shannessy <paul@oshannessy.com> <poshannessy@fb.com>
|
||||
Paul Shen <paul@mnml0.com> <paulshen@fb.com>
|
||||
Pete Hunt <floydophone@gmail.com>
|
||||
Pete Hunt <floydophone@gmail.com> <pete.hunt@fb.com>
|
||||
Pete Hunt <floydophone@gmail.com> <pete@instagram.com>
|
||||
Sander Spies <sandermail@gmail.com>
|
||||
Sebastian Markbåge <sebastian@calyptus.eu> <sema@fb.com>
|
||||
Stoyan Stefanov <ssttoo@ymail.com>
|
||||
Timothy Yung <yungsters@gmail.com> <yungsters@fb.com>
|
||||
Vjeux <vjeuxx@gmail.com>
|
||||
Vjeux <vjeuxx@gmail.com> <vjeux@fb.com>
|
||||
@@ -4,7 +4,6 @@ node_js:
|
||||
- '0.10'
|
||||
after_script:
|
||||
- curl -F "react=@build/react.js" -F "react.min=@build/react.min.js" -F "transformer=@build/JSXTransformer.js"
|
||||
-F "react-with-addons=@build/react-with-addons.js" -F "react-with-addons.min=@build/react-with-addons.min.js"
|
||||
-F "commit=$TRAVIS_COMMIT" -F "date=`git log --format='%ct' -1`" -F "pull_request=$TRAVIS_PULL_REQUEST"
|
||||
-F "token=$SECRET_TOKEN" -F "branch=$TRAVIS_BRANCH" $SERVER
|
||||
env:
|
||||
|
||||
50
AUTHORS
@@ -1,50 +0,0 @@
|
||||
Alexander Solovyov <alexander@solovyov.net>
|
||||
Andrew Zich <azich@fb.com>
|
||||
Andrey Popp <8mayday@gmail.com>
|
||||
Ben Alpert <spicyjalapeno@gmail.com>
|
||||
Ben Newman <bn@cs.stanford.edu>
|
||||
Brian Rue <brian@rollbar.com>
|
||||
Cam Spiers <camspiers@gmail.com>
|
||||
Cat Chen <catchen@fb.com>
|
||||
Cheng Lou <chenglou92@gmail.com>
|
||||
Christian Roman <chroman16@gmail.com>
|
||||
Clay Allsopp <clay.allsopp@gmail.com>
|
||||
Connor McSheffrey <connor.mcsheffrey@gmail.com>
|
||||
Dan Schafer <dschafer@fb.com>
|
||||
Daniel Gasienica <dgasienica@zynga.com>
|
||||
Daniel Miladinov <dmiladinov@wingspan.com>
|
||||
Danny Ben-David <dannybd@fb.com>
|
||||
David Hu <davidhu91@gmail.com>
|
||||
Eric Clemmons <eric@smarterspam.com>
|
||||
Greg Roodt <groodt@gmail.com>
|
||||
Harry Hull <harry.hull1@gmail.com>
|
||||
Hugo Jobling <me@thisishugo.com>
|
||||
Ian Obermiller <iano@fb.com>
|
||||
Isaac Salier-Hellendag <isaac@fb.com>
|
||||
Jakub Malinowski <jakubmal@gmail.com>
|
||||
James Ide <ide@fb.com>
|
||||
Jamie Wong <jamie.lf.wong@gmail.com>
|
||||
Jan Kassens <jkassens@fb.com>
|
||||
Jeff Morrison <jeff@anafx.com>
|
||||
Jeffrey Lin <lin.jeffrey@gmail.com>
|
||||
Jordan Walke <jordojw@gmail.com>
|
||||
Josh Duck <josh@fb.com>
|
||||
Keito Uchiyama <keito@fb.com>
|
||||
Kunal Mehta <k.mehta@berkeley.edu>
|
||||
Laurence Rowe <l@lrowe.co.uk>
|
||||
Marshall Roch <mroch@fb.com>
|
||||
Martin Konicek <mkonicek@fb.com>
|
||||
Mathieu M-Gosselin <mathieumg@gmail.com>
|
||||
Nick Gavalas <njg57@cornell.edu>
|
||||
Owen Coutts <owenc@fb.com>
|
||||
Paul O’Shannessy <paul@oshannessy.com>
|
||||
Paul Seiffert <paul.seiffert@gmail.com>
|
||||
Paul Shen <paul@mnml0.com>
|
||||
Pete Hunt <floydophone@gmail.com>
|
||||
Peter Cottle <pcottle@fb.com>
|
||||
Sander Spies <sandermail@gmail.com>
|
||||
Sebastian Markbåge <sebastian@calyptus.eu>
|
||||
Stoyan Stefanov <ssttoo@ymail.com>
|
||||
Timothy Yung <yungsters@gmail.com>
|
||||
Vjeux <vjeuxx@gmail.com>
|
||||
Zach Bruggeman <zbruggeman@me.com>
|
||||
49
CHANGELOG.md
@@ -1,52 +1,3 @@
|
||||
## 0.5.1 (October 29, 2013)
|
||||
|
||||
### React
|
||||
|
||||
* Fixed bug with `<input type="range">` and selection events.
|
||||
* Fixed bug with selection and focus.
|
||||
* Made it possible to unmount components from the document root.
|
||||
* Fixed bug for `disabled` attribute handling on non-`<input>` elements.
|
||||
|
||||
### React with Addons
|
||||
|
||||
* Fixed bug with transition and animation event detection.
|
||||
|
||||
|
||||
## 0.5.0 (October 16, 2013)
|
||||
|
||||
### React
|
||||
|
||||
* Memory usage improvements - reduced allocations in core which will help with GC pauses
|
||||
* Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
|
||||
* Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
|
||||
* Support for Selection events.
|
||||
* Support for [Composition events](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
|
||||
* Support for additional DOM properties (`charSet`, `content`, `form`, `httpEquiv`, `rowSpan`, `autoCapitalize`).
|
||||
* Support for additional SVG properties (`rx`, `ry`).
|
||||
* Support for using `getInitialState` and `getDefaultProps` in mixins.
|
||||
* Support mounting into iframes.
|
||||
* Bug fixes for controlled form components.
|
||||
* Bug fixes for SVG element creation.
|
||||
* Added `React.version`.
|
||||
* Added `React.isValidClass` - Used to determine if a value is a valid component constructor.
|
||||
* Removed `React.autoBind` - This was deprecated in v0.4 and now properly removed.
|
||||
* Renamed `React.unmountAndReleaseReactRootNode` to `React.unmountComponentAtNode`.
|
||||
* Began laying down work for refined performance analysis.
|
||||
* Better support for server-side rendering - [react-page](https://github.com/facebook/react-page) has helped improve the stability for server-side rendering.
|
||||
* Made it possible to use React in environments enforcing a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy). This also makes it possible to use React to build Chrome extensions.
|
||||
|
||||
### React with Addons (New!)
|
||||
|
||||
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](http://facebook.github.io/react/docs/addons.html).
|
||||
|
||||
### JSX
|
||||
|
||||
* No longer transform `class` to `className` as part of the transform! This is a breaking change - if you were using `class`, you *must* change this to `className` or your components will be visually broken.
|
||||
* Added warnings to the in-browser transformer to make it clear it is not intended for production use.
|
||||
* Improved compatibility for Windows
|
||||
* Improved support for maintaining line numbers when transforming.
|
||||
|
||||
|
||||
## 0.4.1 (July 26, 2013)
|
||||
|
||||
### React
|
||||
|
||||
27
Gruntfile.js
@@ -52,48 +52,27 @@ module.exports = function(grunt) {
|
||||
|
||||
grunt.registerMultiTask('npm', npmTask);
|
||||
|
||||
// Check that the version we're exporting is the same one we expect in the
|
||||
// package. This is not an ideal way to do this, but makes sure that we keep
|
||||
// them in sync.
|
||||
var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;
|
||||
grunt.registerTask('version-check', function() {
|
||||
var version = reactVersionExp.exec(
|
||||
grunt.file.read('./build/modules/React.js')
|
||||
)[1];
|
||||
var expectedVersion = grunt.config.data.pkg.version;
|
||||
if (version !== expectedVersion) {
|
||||
grunt.log.error('Versions do not match. Expected %s, saw %s', expectedVersion, version);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
grunt.registerTask('build:basic', ['jsx:debug', 'version-check', 'browserify:basic']);
|
||||
grunt.registerTask('build:addons', ['jsx:debug', 'browserify:addons']);
|
||||
grunt.registerTask('build:basic', ['jsx:debug', 'browserify:basic']);
|
||||
grunt.registerTask('build:transformer', ['jsx:debug', 'browserify:transformer']);
|
||||
grunt.registerTask('build:min', ['jsx:release', 'version-check', 'browserify:min']);
|
||||
grunt.registerTask('build:addons-min', ['jsx:debug', 'browserify:addonsMin']);
|
||||
grunt.registerTask('build:min', ['jsx:release', 'browserify:min']);
|
||||
grunt.registerTask('build:test', [
|
||||
'jsx:jasmine',
|
||||
'jsx:test',
|
||||
'version-check',
|
||||
'populist:jasmine',
|
||||
'populist:test'
|
||||
]);
|
||||
|
||||
grunt.registerTask('test', ['build:test', 'build:basic', 'phantom:run']);
|
||||
grunt.registerTask('test', ['build:test', 'phantom:run']);
|
||||
grunt.registerTask('npm:test', ['build', 'npm:pack']);
|
||||
|
||||
// Optimized build task that does all of our builds. The subtasks will be run
|
||||
// in order so we can take advantage of that and only run jsx:debug once.
|
||||
grunt.registerTask('build', [
|
||||
'jsx:debug',
|
||||
'version-check',
|
||||
'browserify:basic',
|
||||
'browserify:transformer',
|
||||
'browserify:addons',
|
||||
'jsx:release',
|
||||
'browserify:min',
|
||||
'browserify:addonsMin',
|
||||
'copy:react_docs',
|
||||
'compare_size'
|
||||
]);
|
||||
|
||||
26
README.md
@@ -2,21 +2,21 @@
|
||||
|
||||
React is a JavaScript library for building user interfaces.
|
||||
|
||||
* **Just the UI:** Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it's easy to try it out on a small feature in an existing project.
|
||||
* **Virtual DOM:** React uses a *virtual DOM* diff implementation for ultra-high performance. It can also render on the server using Node.js — no heavy browser DOM required.
|
||||
* **Data flow:** React implements one-way reactive data flow which reduces boilerplate and is easier to reason about than traditional data binding.
|
||||
* **Declarative:** React uses a declarative paradigm that makes it easier to reason about your application.
|
||||
* **Efficient:** React computes the minimal set of changes necessary to keep your DOM up-to-date.
|
||||
* **Flexible:** React works with the libraries and frameworks that you already know.
|
||||
|
||||
[Learn how to use React in your own project.](http://facebook.github.io/react/docs/getting-started.html)
|
||||
|
||||
## Examples
|
||||
|
||||
We have several examples [on the website](http://facebook.github.io/react/). Here is the first one to get you started:
|
||||
We have several examples [on the website](http://facebook.github.io/react). Here is the first one to get you started:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
var HelloMessage = React.createClass({
|
||||
render: function() {
|
||||
return <div>Hello {this.props.name}</div>;
|
||||
return <div>{'Hello ' + this.props.name}</div>;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -28,7 +28,7 @@ React.renderComponent(
|
||||
|
||||
This example will render "Hello John" into a container on the page.
|
||||
|
||||
You'll notice that we used an XML-like syntax; [we call it JSX](http://facebook.github.io/react/docs/jsx-in-depth.html). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. A simple transform is included with React that allows converting JSX into native JavaScript for browsers to digest.
|
||||
You'll notice that we used an XML-like syntax; [we call it JSX](http://facebook.github.io/react/docs/syntax.html). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. A simple transform is included with React that allows converting JSX into native JavaScript for browsers to digest.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -36,12 +36,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.5.2.js"></script>
|
||||
<script src="http://fb.me/react-0.4.1.min.js"></script>
|
||||
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
|
||||
<script src="http://fb.me/JSXTransformer-0.5.2.js"></script>
|
||||
<script src="http://fb.me/JSXTransformer-0.4.1.js"></script>
|
||||
```
|
||||
|
||||
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.5.2.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.4.1.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:
|
||||
|
||||
@@ -51,7 +51,7 @@ bower install --save react
|
||||
|
||||
## Contribute
|
||||
|
||||
The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too. :) Any feedback you have about using React would be greatly appreciated.
|
||||
The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too :) Any feedback you have about using React would be greatly appreciated.
|
||||
|
||||
### Building Your Copy of React
|
||||
|
||||
@@ -81,10 +81,12 @@ At this point, you should now have a `build/` directory populated with everythin
|
||||
We use grunt to automate many tasks. Run `grunt -h` to see a mostly complete listing. The important ones to know:
|
||||
|
||||
```sh
|
||||
# Build and run tests with PhantomJS
|
||||
# Create test build & run tests with PhantomJS
|
||||
grunt test
|
||||
# Lint the code with JSHint
|
||||
# Lint the core library code with JSHint
|
||||
grunt lint
|
||||
# Lint package code
|
||||
grunt lint:package
|
||||
# Wipe out build directory
|
||||
grunt clean
|
||||
```
|
||||
|
||||
49
bin/jsx
@@ -2,11 +2,54 @@
|
||||
"use strict";
|
||||
|
||||
var visitors = require('../vendor/fbtransform/visitors').transformVisitors;
|
||||
var transform = require('jstransform').transform;
|
||||
var transform = require('../vendor/fbtransform/lib/transform').transform;
|
||||
var propagate = require("../vendor/constants").propagate;
|
||||
|
||||
require("commoner").resolve(function(id) {
|
||||
return this.readModuleP(id);
|
||||
var context = this;
|
||||
|
||||
// Note that the result of context.getProvidedP() is cached for the
|
||||
// duration of the build, so it is both consistent and cheap to
|
||||
// evaluate multiple times.
|
||||
return context.getProvidedP().then(function(idToPath) {
|
||||
// If a module declares its own identifier using @providesModule
|
||||
// then that identifier will be a key in the idToPath object.
|
||||
if (idToPath.hasOwnProperty(id)) {
|
||||
return context.readFileP(idToPath[id]);
|
||||
}
|
||||
|
||||
// Otherwise assume the identifier maps directly to a path in the
|
||||
// filesystem.
|
||||
return context.readModuleP(id);
|
||||
});
|
||||
|
||||
}).process(function(id, source) {
|
||||
var context = this;
|
||||
var constants = context.config.constants || {};
|
||||
|
||||
// This is where JSX, ES6, etc. desugaring happens.
|
||||
return transform(visitors.react, source).code;
|
||||
source = transform(visitors.react, source).code;
|
||||
|
||||
// Constant propagation means removing any obviously dead code after
|
||||
// replacing constant expressions with literal (boolean) values.
|
||||
source = propagate(constants, source);
|
||||
|
||||
if (context.config.mocking) {
|
||||
// Make sure there is exactly one newline at the end of the module.
|
||||
source = source.replace(/\s+$/m, "\n");
|
||||
|
||||
return context.getProvidedP().then(function(idToPath) {
|
||||
if (id !== "mock-modules" &&
|
||||
id !== "mocks" &&
|
||||
id !== "test/all" &&
|
||||
idToPath.hasOwnProperty("mock-modules")) {
|
||||
return source + '\nrequire("mock-modules").register(' +
|
||||
JSON.stringify(id) + ', module);\n';
|
||||
}
|
||||
|
||||
return source;
|
||||
});
|
||||
}
|
||||
|
||||
return source;
|
||||
});
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
|
||||
var visitors = require('../vendor/fbtransform/visitors').transformVisitors;
|
||||
var transform = require('jstransform').transform;
|
||||
var propagate = require("../vendor/constants").propagate;
|
||||
|
||||
require("commoner").resolve(function(id) {
|
||||
var context = this;
|
||||
|
||||
// Note that the result of context.getProvidedP() is cached for the
|
||||
// duration of the build, so it is both consistent and cheap to
|
||||
// evaluate multiple times.
|
||||
return context.getProvidedP().then(function(idToPath) {
|
||||
// If a module declares its own identifier using @providesModule
|
||||
// then that identifier will be a key in the idToPath object.
|
||||
if (idToPath.hasOwnProperty(id)) {
|
||||
return context.readFileP(idToPath[id]);
|
||||
}
|
||||
|
||||
// Otherwise assume the identifier maps directly to a path in the
|
||||
// filesystem.
|
||||
return context.readModuleP(id);
|
||||
});
|
||||
|
||||
}).process(function(id, source) {
|
||||
var context = this;
|
||||
var constants = context.config.constants || {};
|
||||
|
||||
// This is where JSX, ES6, etc. desugaring happens.
|
||||
source = transform(visitors.react, source).code;
|
||||
|
||||
// Constant propagation means removing any obviously dead code after
|
||||
// replacing constant expressions with literal (boolean) values.
|
||||
source = propagate(constants, source);
|
||||
|
||||
if (context.config.mocking) {
|
||||
// Make sure there is exactly one newline at the end of the module.
|
||||
source = source.replace(/\s+$/m, "\n");
|
||||
|
||||
return context.getProvidedP().then(function(idToPath) {
|
||||
if (id !== "mock-modules" &&
|
||||
id !== "mocks" &&
|
||||
id !== "test/all" &&
|
||||
idToPath.hasOwnProperty("mock-modules")) {
|
||||
return source + '\nrequire("mock-modules").register(' +
|
||||
JSON.stringify(id) + ', module);\n';
|
||||
}
|
||||
|
||||
return source;
|
||||
});
|
||||
}
|
||||
|
||||
return source;
|
||||
});
|
||||
@@ -3,7 +3,7 @@ source 'https://rubygems.org'
|
||||
gem 'rake'
|
||||
|
||||
# jekyll, which builds it all
|
||||
gem 'jekyll', '~>1.3.0'
|
||||
gem 'jekyll', '~>1.0'
|
||||
|
||||
# JSON
|
||||
gem 'json'
|
||||
|
||||
@@ -4,47 +4,40 @@ GEM
|
||||
classifier (1.3.3)
|
||||
fast-stemmer (>= 1.0.0)
|
||||
colorator (0.1)
|
||||
commander (4.1.5)
|
||||
commander (4.1.3)
|
||||
highline (~> 1.6.11)
|
||||
directory_watcher (1.4.1)
|
||||
fast-stemmer (1.0.2)
|
||||
ffi (1.9.3)
|
||||
highline (1.6.20)
|
||||
jekyll (1.3.0)
|
||||
highline (1.6.19)
|
||||
jekyll (1.0.2)
|
||||
classifier (~> 1.3)
|
||||
colorator (~> 0.1)
|
||||
commander (~> 4.1.3)
|
||||
liquid (~> 2.5.2)
|
||||
listen (~> 1.3)
|
||||
maruku (~> 0.6.0)
|
||||
directory_watcher (~> 1.4.1)
|
||||
kramdown (~> 1.0.2)
|
||||
liquid (~> 2.3)
|
||||
maruku (~> 0.5)
|
||||
pygments.rb (~> 0.5.0)
|
||||
redcarpet (~> 2.3.0)
|
||||
safe_yaml (~> 0.9.7)
|
||||
json (1.8.1)
|
||||
liquid (2.5.4)
|
||||
listen (1.3.1)
|
||||
rb-fsevent (>= 0.9.3)
|
||||
rb-inotify (>= 0.9)
|
||||
rb-kqueue (>= 0.2)
|
||||
safe_yaml (~> 0.7.0)
|
||||
json (1.8.0)
|
||||
kramdown (1.0.2)
|
||||
liquid (2.5.0)
|
||||
maruku (0.6.1)
|
||||
syntax (>= 1.0.0)
|
||||
mini_portile (0.5.2)
|
||||
mini_portile (0.5.1)
|
||||
nokogiri (1.6.0)
|
||||
mini_portile (~> 0.5.0)
|
||||
posix-spawn (0.3.6)
|
||||
pygments.rb (0.5.4)
|
||||
pygments.rb (0.5.0)
|
||||
posix-spawn (~> 0.3.6)
|
||||
yajl-ruby (~> 1.1.0)
|
||||
rake (10.1.0)
|
||||
rake (10.0.4)
|
||||
rb-fsevent (0.9.3)
|
||||
rb-inotify (0.9.2)
|
||||
ffi (>= 0.5.0)
|
||||
rb-kqueue (0.2.0)
|
||||
ffi (>= 0.5.0)
|
||||
redcarpet (2.3.0)
|
||||
safe_yaml (0.9.7)
|
||||
redcarpet (2.2.2)
|
||||
safe_yaml (0.7.1)
|
||||
sanitize (2.0.6)
|
||||
nokogiri (>= 1.4.4)
|
||||
sass (3.2.12)
|
||||
sass (3.2.9)
|
||||
syntax (1.0.0)
|
||||
yajl-ruby (1.1.0)
|
||||
|
||||
@@ -52,7 +45,7 @@ PLATFORMS
|
||||
ruby
|
||||
|
||||
DEPENDENCIES
|
||||
jekyll (~> 1.3.0)
|
||||
jekyll (~> 1.0)
|
||||
json
|
||||
rake
|
||||
rb-fsevent
|
||||
|
||||
@@ -21,7 +21,6 @@ Once you have RubyGems and installed Bundler (via `gem install bundler`), use it
|
||||
```sh
|
||||
$ cd react/docs
|
||||
$ bundle install # Might need sudo.
|
||||
$ npm install # Might need sudo.
|
||||
```
|
||||
|
||||
### Instructions
|
||||
|
||||
@@ -13,8 +13,57 @@ redcarpet:
|
||||
pygments: true
|
||||
name: React
|
||||
markdown: redcarpet
|
||||
react_version: 0.5.2
|
||||
react_version: 0.4.2
|
||||
description: A JavaScript library for building user interfaces
|
||||
relative_permalinks: true
|
||||
paginate: 5
|
||||
paginate_path: /blog/page:num/
|
||||
paginate_path: /blog/page:num
|
||||
nav_docs_sections:
|
||||
- title: Quick Start
|
||||
items:
|
||||
- id: getting-started
|
||||
title: Getting Started
|
||||
- id: tutorial
|
||||
title: Tutorial
|
||||
- title: Guides
|
||||
items:
|
||||
- id: why-react
|
||||
title: Why React?
|
||||
- id: displaying-data
|
||||
title: Displaying Data
|
||||
subitems:
|
||||
- id: jsx-in-depth
|
||||
title: JSX in Depth
|
||||
- id: jsx-gotchas
|
||||
title: JSX Gotchas
|
||||
- id: interactivity-and-dynamic-uis
|
||||
title: Interactivity and Dynamic UIs
|
||||
- id: multiple-components
|
||||
title: Multiple Components
|
||||
- id: reusable-components
|
||||
title: Reusable Components
|
||||
- id: forms
|
||||
title: Forms
|
||||
- id: working-with-the-browser
|
||||
title: Working With the Browser
|
||||
subitems:
|
||||
- id: more-about-refs
|
||||
title: More About Refs
|
||||
- id: tooling-integration
|
||||
title: Tooling Integration
|
||||
- id: examples
|
||||
title: Examples
|
||||
- title: Reference
|
||||
items:
|
||||
- id: top-level-api
|
||||
title: Top-Level API
|
||||
- id: component-api
|
||||
title: Component API
|
||||
- id: component-specs
|
||||
title: Component Specs and Lifecycle
|
||||
- id: tags-and-attributes
|
||||
title: Supported Tags and Attributes
|
||||
- id: events
|
||||
title: Event System
|
||||
- id: dom-differences
|
||||
title: DOM Differences
|
||||
|
||||
@@ -15,7 +15,6 @@ $contentPadding: 20px;
|
||||
$columnWidth: 280px;
|
||||
$columnGutter: 40px;
|
||||
$twoColumnWidth: 2 * $columnWidth + $columnGutter;
|
||||
$navHeight: 50px;
|
||||
|
||||
|
||||
|
||||
@@ -43,7 +42,7 @@ html {
|
||||
|
||||
|
||||
.container {
|
||||
padding-top: $navHeight;
|
||||
padding-top: 50px;
|
||||
min-width: $contentWidth + (2 * $contentPadding);
|
||||
}
|
||||
|
||||
@@ -74,23 +73,6 @@ li {
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
// Make header navigation linkable and on the screen. Used in documentation and
|
||||
// blog posts.
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
.anchor {
|
||||
margin-top: -$navHeight;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
&:hover .hash-link {
|
||||
display: inline;
|
||||
}
|
||||
}
|
||||
.hash-link {
|
||||
color: $mediumTextColor;
|
||||
display: none;
|
||||
}
|
||||
|
||||
// Main Nav
|
||||
|
||||
.nav-main {
|
||||
@@ -99,7 +81,7 @@ h1, h2, h3, h4, h5, h6 {
|
||||
color: $lightTextColor;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
height: $navHeight;
|
||||
height: 50px;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, .5);
|
||||
width: 100%;
|
||||
z-index: 100;
|
||||
@@ -121,9 +103,9 @@ h1, h2, h3, h4, h5, h6 {
|
||||
padding: 0 8px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
line-height: $navHeight;
|
||||
line-height: 50px;
|
||||
display: inline-block;
|
||||
height: $navHeight;
|
||||
height: 50px;
|
||||
color: $mediumTextColor;
|
||||
|
||||
&:hover {
|
||||
@@ -141,7 +123,7 @@ h1, h2, h3, h4, h5, h6 {
|
||||
.nav-home {
|
||||
color: #00d8ff;
|
||||
font-size: 24px;
|
||||
line-height: $navHeight;
|
||||
line-height: 50px;
|
||||
}
|
||||
|
||||
.nav-logo {
|
||||
@@ -387,8 +369,6 @@ section.black content {
|
||||
*/
|
||||
|
||||
.blogContent {
|
||||
@include clearfix;
|
||||
|
||||
padding-top: 20px;
|
||||
|
||||
blockquote {
|
||||
@@ -411,7 +391,6 @@ section.black content {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
|
||||
// H2s form documentation topic dividers. Extra space helps.
|
||||
h2 {
|
||||
margin-top: 30px;
|
||||
@@ -459,7 +438,7 @@ section.black content {
|
||||
}
|
||||
|
||||
.playgroundPreview {
|
||||
padding: 0;
|
||||
padding: 14px;
|
||||
width: 600px;
|
||||
|
||||
pre {
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
- title: Quick Start
|
||||
items:
|
||||
- id: getting-started
|
||||
title: Getting Started
|
||||
- id: tutorial
|
||||
title: Tutorial
|
||||
- title: Guides
|
||||
items:
|
||||
- id: why-react
|
||||
title: Why React?
|
||||
- id: displaying-data
|
||||
title: Displaying Data
|
||||
subitems:
|
||||
- id: jsx-in-depth
|
||||
title: JSX in Depth
|
||||
- id: jsx-gotchas
|
||||
title: JSX Gotchas
|
||||
- id: interactivity-and-dynamic-uis
|
||||
title: Interactivity and Dynamic UIs
|
||||
- id: multiple-components
|
||||
title: Multiple Components
|
||||
- id: reusable-components
|
||||
title: Reusable Components
|
||||
- id: forms
|
||||
title: Forms
|
||||
- id: working-with-the-browser
|
||||
title: Working With the Browser
|
||||
subitems:
|
||||
- id: more-about-refs
|
||||
title: More About Refs
|
||||
- id: tooling-integration
|
||||
title: Tooling Integration
|
||||
- id: addons
|
||||
title: Add-Ons
|
||||
subitems:
|
||||
- id: animation
|
||||
title: Animation
|
||||
- id: two-way-binding-helpers
|
||||
title: Two-Way Binding Helpers
|
||||
- id: class-name-manipulation
|
||||
title: Class Name Manipulation
|
||||
- id: examples
|
||||
title: Examples
|
||||
- title: Reference
|
||||
items:
|
||||
- id: top-level-api
|
||||
title: Top-Level API
|
||||
- id: component-api
|
||||
title: Component API
|
||||
- id: component-specs
|
||||
title: Component Specs and Lifecycle
|
||||
- id: tags-and-attributes
|
||||
title: Supported Tags and Attributes
|
||||
- id: events
|
||||
title: Event System
|
||||
- id: dom-differences
|
||||
title: DOM Differences
|
||||
@@ -1,30 +0,0 @@
|
||||
- title: Tips
|
||||
items:
|
||||
- id: introduction
|
||||
title: Introduction
|
||||
- id: inline-styles
|
||||
title: Inline Styles
|
||||
- id: if-else-in-JSX
|
||||
title: If-Else in JSX
|
||||
- id: self-closing-tag
|
||||
title: Self-Closing Tag
|
||||
- id: maximum-number-of-jsx-root-nodes
|
||||
title: Maximum Number of JSX Root Nodes
|
||||
- id: style-props-value-px
|
||||
title: Shorthand for Specifying Pixel Values in style props
|
||||
- id: children-props-type
|
||||
title: Type of the Children props
|
||||
- id: controlled-input-null-value
|
||||
title: Value of null for Controlled Input
|
||||
- id: componentWillReceiveProps-not-triggered-after-mounting
|
||||
title: componentWillReceiveProps Not Triggered After Mounting
|
||||
- id: props-in-getInitialState-as-anti-pattern
|
||||
title: Props in getInitialState Is an Anti-Pattern
|
||||
- id: dom-event-listeners
|
||||
title: DOM Event Listeners in a Component
|
||||
- id: initial-ajax
|
||||
title: Load Initial Data via AJAX
|
||||
- id: false-in-jsx
|
||||
title: False in JSX
|
||||
- id: communicate-between-components
|
||||
title: Communicate Between Components
|
||||
@@ -1,6 +1,5 @@
|
||||
<div class="nav-docs">
|
||||
<!-- Docs Nav -->
|
||||
{% for section in site.data.nav_docs %}
|
||||
{% for section in site.nav_docs_sections %}
|
||||
<div class="nav-docs-section">
|
||||
<h3>{{ section.title }}</h3>
|
||||
<ul>
|
||||
@@ -25,18 +24,4 @@
|
||||
</ul>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
<!-- Tips Nav -->
|
||||
{% for section in site.data.nav_tips %}
|
||||
<div class="nav-docs-section">
|
||||
<h3>{{ section.title }}</h3>
|
||||
<ul>
|
||||
{% for item in section.items %}
|
||||
<li>
|
||||
<a href="/react/tips/{{ item.id }}.html"{% if page.id == item.id %} class="active"{% endif %}>{{ item.title }}</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
@@ -18,7 +18,7 @@ var Timer = React.createClass({\n\
|
||||
},\n\
|
||||
render: function() {\n\
|
||||
return React.DOM.div({},\n\
|
||||
'Seconds Elapsed: ', this.state.secondsElapsed\n\
|
||||
'Seconds Elapsed: ' + this.state.secondsElapsed\n\
|
||||
);\n\
|
||||
}\n\
|
||||
});\n\
|
||||
|
||||
@@ -22,8 +22,7 @@ var CodeMirrorEditor = React.createClass({
|
||||
mode: 'javascript',
|
||||
lineNumbers: false,
|
||||
matchBrackets: true,
|
||||
theme: 'solarized-light',
|
||||
readOnly: this.props.readOnly
|
||||
theme: 'solarized-light'
|
||||
});
|
||||
this.editor.on('change', this.onChange);
|
||||
this.onChange();
|
||||
@@ -45,7 +44,7 @@ var CodeMirrorEditor = React.createClass({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={this.props.className}>
|
||||
<div class={this.props.className}>
|
||||
{editor}
|
||||
</div>
|
||||
);
|
||||
@@ -77,22 +76,22 @@ var ReactPlayground = React.createClass({
|
||||
content =
|
||||
<CodeMirrorEditor
|
||||
onChange={this.bindState('code')}
|
||||
className="playgroundStage"
|
||||
class="playgroundStage"
|
||||
codeText={this.state.code}
|
||||
/>;
|
||||
} else if (this.state.mode === this.MODES.JS) {
|
||||
content =
|
||||
<div className="playgroundJS playgroundStage">
|
||||
{this.getDesugaredCode()}
|
||||
<div class="playgroundJS playgroundStage">
|
||||
{this.getDesugaredCode()}
|
||||
</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="playground">
|
||||
<div className="playgroundCode">
|
||||
<div class="playground">
|
||||
<div class="playgroundCode">
|
||||
{content}
|
||||
</div>
|
||||
<div className="playgroundPreview">
|
||||
<div class="playgroundPreview">
|
||||
<div ref="mount" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -112,18 +111,17 @@ var ReactPlayground = React.createClass({
|
||||
} catch (e) { }
|
||||
|
||||
try {
|
||||
var desugaredCode = this.getDesugaredCode();
|
||||
if (this.props.renderCode) {
|
||||
React.renderComponent(
|
||||
<CodeMirrorEditor codeText={desugaredCode} readOnly={true} />,
|
||||
<pre>{this.getDesugaredCode()}</pre>,
|
||||
mountNode
|
||||
);
|
||||
} else {
|
||||
eval(desugaredCode);
|
||||
eval(this.getDesugaredCode());
|
||||
}
|
||||
} catch (e) {
|
||||
React.renderComponent(
|
||||
<div content={e.toString()} className="playgroundError" />,
|
||||
<div content={e.toString()} class="playgroundError" />,
|
||||
mountNode
|
||||
);
|
||||
}
|
||||
|
||||
@@ -74,7 +74,6 @@
|
||||
</footer>
|
||||
</div>
|
||||
<div id="fb-root"></div>
|
||||
|
||||
<script>
|
||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
---
|
||||
layout: default
|
||||
sectionid: tips
|
||||
---
|
||||
|
||||
<section class="content wrap documentationContent">
|
||||
{% include nav_docs.html %}
|
||||
|
||||
<div class="inner-content">
|
||||
<h1>{{ page.title }}</h1>
|
||||
<div class="subHeader">{{ page.description }}</div>
|
||||
{{ content }}
|
||||
|
||||
<div class="docs-prevnext">
|
||||
{% if page.prev %}
|
||||
<a class="docs-prev" href="/react/tips/{{ page.prev }}">← Prev</a>
|
||||
{% endif %}
|
||||
{% if page.next %}
|
||||
<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>
|
||||
@@ -11,7 +11,7 @@ class Redcarpet::Render::HTML
|
||||
.gsub(/\s+/, "-")
|
||||
.gsub(/[^A-Za-z0-9\-_.]/, "")
|
||||
|
||||
return "<h#{level}><a class=\"anchor\" name=\"#{clean_title}\"></a>#{title} <a class=\"hash-link\" href=\"##{clean_title}\">#</a></h#{level}>"
|
||||
return "<h#{level} id=\"#{clean_title}\">#{title}</h#{level}>"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
---
|
||||
title: "React v0.5"
|
||||
layout: post
|
||||
author: Paul O'Shannessy
|
||||
---
|
||||
|
||||
This release is the result of several months of hard work from members of the team and the community. While there are no groundbreaking changes in core, we've worked hard to improve performance and memory usage. We've also worked hard to make sure we are being consistent in our usage of DOM properties.
|
||||
|
||||
The biggest change you'll notice as a developer is that we no longer support `class` in JSX as a way to provide CSS classes. Since this prop was being converted to `className` at the transform step, it caused some confusion when trying to access it in composite components. As a result we decided to make our DOM properties mirror their counterparts in the JS DOM API. There are [a few exceptions](https://github.com/facebook/react/blob/master/src/dom/DefaultDOMPropertyConfig.js#L156) where we deviate slightly in an attempt to be consistent internally.
|
||||
|
||||
The other major change in v0.5 is that we've added an additional build - `react-with-addons` - which adds support for some extras that we've been working on including animations and two-way binding. [Read more about these addons in the docs](/react/docs/addons.html).
|
||||
|
||||
## Thanks to Our Community
|
||||
|
||||
We added *22 new people* to the list of authors since we launched React v0.4.1 nearly 3 months ago. With a total of 48 names in our `AUTHORS` file, that means we've nearly doubled the number of contributors in that time period. We've seen the number of people contributing to discussion on IRC, mailing lists, Stack Overflow, and GitHub continue rising. We've also had people tell us about talks they've given in their local community about React.
|
||||
|
||||
It's been awesome to see the things that people are building with React, and we can't wait to see what you come up with next!
|
||||
|
||||
|
||||
## Changelog
|
||||
|
||||
### React
|
||||
|
||||
* Memory usage improvements - reduced allocations in core which will help with GC pauses
|
||||
* Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
|
||||
* Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
|
||||
* Support for Selection events.
|
||||
* Support for [Composition events](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
|
||||
* Support for additional DOM properties (`charSet`, `content`, `form`, `httpEquiv`, `rowSpan`, `autoCapitalize`).
|
||||
* Support for additional SVG properties (`rx`, `ry`).
|
||||
* Support for using `getInitialState` and `getDefaultProps` in mixins.
|
||||
* Support mounting into iframes.
|
||||
* Bug fixes for controlled form components.
|
||||
* Bug fixes for SVG element creation.
|
||||
* Added `React.version`.
|
||||
* Added `React.isValidClass` - Used to determine if a value is a valid component constructor.
|
||||
* Removed `React.autoBind` - This was deprecated in v0.4 and now properly removed.
|
||||
* Renamed `React.unmountAndReleaseReactRootNode` to `React.unmountComponentAtNode`.
|
||||
* Began laying down work for refined performance analysis.
|
||||
* Better support for server-side rendering - [react-page](https://github.com/facebook/react-page) has helped improve the stability for server-side rendering.
|
||||
* Made it possible to use React in environments enforcing a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy). This also makes it possible to use React to build Chrome extensions.
|
||||
|
||||
### React with Addons (New!)
|
||||
|
||||
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](/react/docs/addons.html).
|
||||
|
||||
### JSX
|
||||
|
||||
* No longer transform `class` to `className` as part of the transform! This is a breaking change - if you were using `class`, you *must* change this to `className` or your components will be visually broken.
|
||||
* Added warnings to the in-browser transformer to make it clear it is not intended for production use.
|
||||
* Improved compatibility for Windows
|
||||
* Improved support for maintaining line numbers when transforming.
|
||||
@@ -1,25 +0,0 @@
|
||||
---
|
||||
title: "React v0.5.1"
|
||||
layout: post
|
||||
author: Paul O'Shannessy
|
||||
---
|
||||
|
||||
This release focuses on fixing some small bugs that have been uncovered over the past two weeks. I would like to thank everybody involved, specifically members of the community who fixed half of the issues found. Thanks to [Ben Alpert][1], [Andrey Popp][2], and [Laurence Rowe][3] for their contributions!
|
||||
|
||||
## Changelog
|
||||
|
||||
### React
|
||||
|
||||
* Fixed bug with `<input type="range">` and selection events.
|
||||
* Fixed bug with selection and focus.
|
||||
* Made it possible to unmount components from the document root.
|
||||
* Fixed bug for `disabled` attribute handling on non-`<input>` elements.
|
||||
|
||||
### React with Addons
|
||||
|
||||
* Fixed bug with transition and animation event detection.
|
||||
|
||||
[1]: https://github.com/spicyj
|
||||
[2]: https://github.com/andreypopp
|
||||
[3]: https://github.com/lrowe
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
---
|
||||
title: "Thinking in React"
|
||||
layout: post
|
||||
author: Pete Hunt
|
||||
---
|
||||
|
||||
React is, in my opinion, the premier way to build big, fast Web apps with JavaScript. It's scaled very well for us at Facebook and Instagram.
|
||||
|
||||
One of the many great parts of React is how it makes you think about apps as you build them. In this post I'll walk you through the thought process of building a searchable product data table using React.
|
||||
|
||||
## Start with a mock
|
||||
|
||||
Imagine that we already have a JSON API and a mock from our designer. Our designer apparently isn't very good because the mock looks like this:
|
||||
|
||||

|
||||
|
||||
Our JSON API returns some data that looks like this:
|
||||
|
||||
```
|
||||
[
|
||||
{category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
|
||||
{category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
|
||||
{category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
|
||||
{category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
|
||||
{category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
|
||||
{category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
|
||||
];
|
||||
```
|
||||
|
||||
## Step 1: break the UI into a component hierarchy
|
||||
|
||||
The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you're working with a designer they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!
|
||||
|
||||
But how do you know what should be its own component? Just use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing it should be decomposed into smaller subcomponents.
|
||||
|
||||
Since you're often displaying a JSON data model to a user, you'll find that if your model was built correctly your UI (and therefore your component structure) will map nicely onto it. That's because user interfaces and data models tend to adhere to the same *information architecture* which means the work of separating your UI into components is often trivial. Just break it up into components that represent exactly one piece of your data model.
|
||||
|
||||

|
||||
|
||||
You'll see here that we have five components in our simple app. I've italicized the data each component represents.
|
||||
|
||||
1. **`FilterableProductTable` (orange):** contains the entirety of the example
|
||||
2. **`SearchBar` (blue):** receives all *user input*
|
||||
3. **`ProductTable` (green):** displays and filters the *data collection* based on *user input*
|
||||
4. **`ProductCategoryRow` (turquoise):** displays a heading for each *category*
|
||||
5. **`ProductRow` (red):** displays a row for each *product*
|
||||
|
||||
If you look at `ProductTable` you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference and there's an argument to be made either way. For this example I left it as part of `ProductTable` because it is part of rendering the *data collection* which is `ProductTable`'s responsibility. However if this header grows to be complex (i.e. if we were to add affordances for sorting) it would certainly make sense to make this its own `ProductTableHeader` component.
|
||||
|
||||
Now that we've identified the components in our mock, let's arrange them into a hierarchy. This is easy. Components that appear within another component in the mock should appear as a child in the hierarchy:
|
||||
|
||||
* `FilterableProductTable`
|
||||
* `SearchBar`
|
||||
* `ProductTable`
|
||||
* `ProductCategoryRow`
|
||||
* `ProductRow`
|
||||
|
||||
## Step 2: Build a static version in React
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/6wQMG/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 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.
|
||||
|
||||
To build a static version of your app that renders your data model you'll want to build components that reuse other components and pass data using *props*. *props* are a way of passing data from parent to child. If you're familiar with the concept of *state*, **don't use state at all** to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app you don't need it.
|
||||
|
||||
You can build top-down or bottom-up. That is, you can either start with building the components higher up in the hierarchy (i.e. starting with `FilterableProductTable`) or with the ones lower in it (`ProductRow`). In simpler examples it's usually easier to go top-down and on larger projects it's easier to go bottom-up and write tests as you build.
|
||||
|
||||
At the end of this step you'll have a library of reusable components that render your data model. The components will only have `render()` methods since this is a static version of your app. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. If you make a change to your underlying data model and call `renderComponent()` again the UI will be updated. It's easy to see how your UI is updated and where to make changes since there's nothing complicated going on since React's **one-way data flow** (also called *one-way binding*) keeps everything modular, easy to reason about, and fast.
|
||||
|
||||
Simply refer to the [React docs](http://facebook.github.io/react/docs/) if you need help executing this step.
|
||||
|
||||
### A brief interlude: props vs state
|
||||
|
||||
There are two types of "model" data in React: props and state. It's important to understand the distinction between the two; skim [the official React docs](http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html) if you aren't sure what the difference is.
|
||||
|
||||
## Step 3: Identify the minimal (but complete) representation of UI state
|
||||
|
||||
To make your UI interactive you need to be able to trigger changes to your underlying data model. React makes this easy with **state**.
|
||||
|
||||
To build your app correctly you first need to think of the minimal set of mutable state that your app needs. The key here is DRY: *Don't Repeat Yourself*. Figure out what the absolute minimal representation of the state of your application needs to be and compute everything else you need on-demand. For example, if you're building a TODO list, just keep an array of the TODO items around; don't keep a separate state variable for the count. Instead, when you want to render the TODO count simply take the length of the TODO items array.
|
||||
|
||||
Think of all of the pieces of data in our example application. We have:
|
||||
|
||||
* The original list of products
|
||||
* The search text the user has entered
|
||||
* The value of the checkbox
|
||||
* The filtered list of products
|
||||
|
||||
Let's go through each one and figure out which one is state. Simply ask three questions about each piece of data:
|
||||
|
||||
1. Is it passed in from a parent via props? If so, it probably isn't state.
|
||||
2. Does it change over time? If not, it probably isn't state.
|
||||
3. Can you compute it based on any other state or props in your component? If so, it's not state.
|
||||
|
||||
The original list of products is passed in as props, so that's not state. The search text and the checkbox seem to be state since they change over time and can't be computed from anything. And finally, the filtered list of products isn't state because it can be computed by combining the original list of products with the search text and value of the checkbox.
|
||||
|
||||
So finally, our state is:
|
||||
|
||||
* The search text the user has entered
|
||||
* The value of the checkbox
|
||||
|
||||
## Step 4: Identify where your state should live
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/QvHnx/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.
|
||||
|
||||
Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. **This is often the most challenging part for newcomers to understand,** so follow these steps to figure it out:
|
||||
|
||||
For each piece of state in your application:
|
||||
|
||||
* Identify every component that renders something based on that state.
|
||||
* Find a common owner component (a single component above all the components that need the state in the hierarchy).
|
||||
* Either the common owner or another component higher up in the hierarchy should own the state.
|
||||
* If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.
|
||||
|
||||
Let's run through this strategy for our application:
|
||||
|
||||
* `ProductTable` needs to filter the product list based on state and `SearchBar` needs to display the search text and checked state.
|
||||
* The common owner component is `FilterableProductTable`.
|
||||
* It conceptually makes sense for the filter text and checked value to live in `FilterableProductTable`
|
||||
|
||||
Cool, so we've decided that our state lives in `FilterableProductTable`. First, add a `getInitialState()` method to `FilterableProductTable` that returns `{filterText: '', inStockOnly: false}` to reflect the initial state of your application. Then pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as a prop. Finally, use these props to filter the rows in `ProductTable` and set the values of the form fields in `SearchBar`.
|
||||
|
||||
You can start seeing how your application will behave: set `filterText` to `"ball"` and refresh your app. You'll see the data table is updated correctly.
|
||||
|
||||
## Step 5: Add inverse data flow
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/3Vs3Q/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`.
|
||||
|
||||
React makes this data flow explicit to make it easy to understand how your program works, but it does require a little more typing than traditional two-way data binding. React provides an add-on called `ReactLink` to make this pattern as convenient as two-way binding, but for the purpose of this post we'll keep everything explicit.
|
||||
|
||||
If you try to type or check the box in the current version of the example you'll see that React ignores your input. This is intentional, as we've set the `value` prop of the `input` to always be equal to the `state` passed in from `FilterableProductTable`.
|
||||
|
||||
Let's think about what we want to happen. We want to make sure that whenever the user changes the form we update the state to reflect the user input. Since components should only update their own state, `FilterableProductTable` will pass a callback to `SearchBar` that will fire whenever the state should be updated. We can use the `onChange` event on the inputs to be notified of it. And the callback passed by `FilterableProductTable` will call `setState()` and the app will be updated.
|
||||
|
||||
Though this sounds like a lot it's really just a few lines of code. And it's really explicit how your data is flowing throughout the app.
|
||||
|
||||
## And that's it
|
||||
|
||||
Hopefully this gives you an idea of how to think about building components and applications with React. While it may be a little more typing than you're used to, remember that code is read far more than it's written, and it's extremely easy to read this modular, explicit code. As you start to build large libraries of components you'll appreciate this explicitness and modularity, and with code reuse your lines of code will start to shrink :)
|
||||
@@ -1,125 +0,0 @@
|
||||
---
|
||||
title: "Community Round-up #10"
|
||||
layout: post
|
||||
author: Vjeux
|
||||
---
|
||||
|
||||
This is the 10th round-up already and React has come quite far since it was open sourced. Almost all new web projects at Khan Academy, Facebook, and Instagram are being developed using React. React has been deployed in a variety of contexts: a Chrome extension, a Windows 8 application, mobile websites, and desktop websites supporting Internet Explorer 8! Language-wise, React is not only being used within JavaScript but also CoffeeScript and ClojureScript.
|
||||
|
||||
The best part is that no drastic changes have been required to support all those use cases. Most of the efforts were targeted at polishing edge cases, performance improvements, and documentation.
|
||||
|
||||
## Khan Academy - Officially moving to React
|
||||
|
||||
[Joel Burget](http://joelburget.com/) announced at Hack Reactor that new front-end code at Khan Academy should be written in React!
|
||||
|
||||
> How did we get the rest of the team to adopt React? Using interns as an attack vector! Most full-time devs had already been working on their existing projects for a while and weren't looking to try something new at the time, but our class of summer interns was just arriving. For whatever reason, a lot of them decided to try React for their projects. Then mentors became exposed through code reviews or otherwise touching the new code. In this way React knowledge diffused to almost the whole team over the summer.
|
||||
>
|
||||
> Since the first React checkin on June 5, we've somehow managed to accumulate 23500 lines of jsx (React-flavored js) code. Which is terrifying in a way - that's a lot of code - but also really exciting that it was picked up so quickly.
|
||||
>
|
||||
> We held three meetings about how we should proceed with React. At the first two we decided to continue experimenting with React and deferred a final decision on whether to adopt it. At the third we adopted the policy that new code should be written in React.
|
||||
>
|
||||
> I'm excited that we were able to start nudging code quality forward. However, we still have a lot of work to do! One of the selling points of this transition is adopting a uniform frontend style. We're trying to upgrade all the code from (really old) pure jQuery and (regular old) Backbone views / Handlebars to shiny React. At the moment all we've done is introduce more fragmentation. We won't be gratuitously updating working code (if it ain't broke, don't fix it), but are seeking out parts of the codebase where we can shoot two birds with one stone by rewriting in React while fixing bugs or adding functionality.
|
||||
>
|
||||
> [Read the full article](http://joelburget.com/backbone-to-react/)
|
||||
|
||||
|
||||
## React: Rethinking best practices
|
||||
|
||||
[Pete Hunt](http://www.petehunt.net/)'s talk at JSConf EU 2013 is now available in video.
|
||||
|
||||
<figure><iframe width="600" height="370" src="//www.youtube.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe></figure>
|
||||
|
||||
|
||||
## Server-side React with PHP
|
||||
|
||||
[Stoyan Stefanov](http://www.phpied.com/)'s series of articles on React has two new entries on how to execute React on the server to generate the initial page load.
|
||||
|
||||
> This post is an initial hack to have React components render server-side in PHP.
|
||||
>
|
||||
> - Problem: Build web UIs
|
||||
> - Solution: React
|
||||
> - Problem: UI built in JS is anti-SEO (assuming search engines are still noscript) and bad for perceived performance (blank page till JS arrives)
|
||||
> - Solution: [React page](https://github.com/facebook/react-page) to render the first view
|
||||
> - Problem: Can't host node.js apps / I have tons of PHP code
|
||||
> - Solution: Use PHP then!
|
||||
>
|
||||
> [**Read part 1 ...**](http://www.phpied.com/server-side-react-with-php/)
|
||||
>
|
||||
> [**Read part 2 ...**](http://www.phpied.com/server-side-react-with-php-part-2/)
|
||||
>
|
||||
> Rendered markup on the server:
|
||||
> <figure>[](http://www.phpied.com/server-side-react-with-php-part-2/)</figure>
|
||||
|
||||
|
||||
## TodoMVC Benchmarks
|
||||
|
||||
Webkit has a [TodoMVC Benchmark](https://github.com/WebKit/webkit/tree/master/PerformanceTests/DoYouEvenBench) that compares different frameworks. They recently included React and here are the results (average of 10 runs in Chrome 30):
|
||||
|
||||
- **AngularJS:** 4043ms
|
||||
- **AngularJSPerf:** 3227ms
|
||||
- **BackboneJS:** 1874ms
|
||||
- **EmberJS:** 6822ms
|
||||
- **jQuery:** 14628ms
|
||||
- **React:** 2864ms
|
||||
- **VanillaJS:** 5567ms
|
||||
|
||||
[Try it yourself!](http://www.petehunt.net/react/tastejs/benchmark.html)
|
||||
|
||||
Please don't take those numbers too seriously, they only reflect one very specific use case and are testing code that wasn't written with performance in mind.
|
||||
|
||||
Even though React scores as one of the fastest frameworks in the benchmark, the React code is simple and idiomatic. The only performance tweak used is the following function:
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* This is a completely optional performance enhancement that you can implement
|
||||
* on any React component. If you were to delete this method the app would still
|
||||
* work correctly (and still be very performant!), we just use it as an example
|
||||
* of how little code it takes to get an order of magnitude performance improvement.
|
||||
*/
|
||||
shouldComponentUpdate: function (nextProps, nextState) {
|
||||
return (
|
||||
nextProps.todo.id !== this.props.todo.id ||
|
||||
nextProps.todo !== this.props.todo ||
|
||||
nextProps.editing !== this.props.editing ||
|
||||
nextState.editText !== this.state.editText
|
||||
);
|
||||
},
|
||||
```
|
||||
|
||||
By default, React "re-renders" all the components when anything changes. This is usually fast enough that you don't need to care. However, you can provide a function that can tell whether there will be any change based on the previous and next states and props. If it is faster than re-rendering the component, then you get a performance improvement.
|
||||
|
||||
The fact that you can control when components are rendered is a very important characteristic of React as it gives you control over its performance. We are going to talk more about performance in the future, stay tuned.
|
||||
|
||||
## Guess the filter
|
||||
|
||||
[Connor McSheffrey](http://conr.me) implemented a small game using React. The goal is to guess which filter has been used to create the Instagram photo.
|
||||
<figure>[](http://guessthefilter.com/)</figure>
|
||||
|
||||
|
||||
## React vs FruitMachine
|
||||
|
||||
[Andrew Betts](http://trib.tv/), director of the [Financial Times Labs](http://labs.ft.com/), posted an article comparing [FruitMachine](https://github.com/ftlabs/fruitmachine) and React.
|
||||
|
||||
> Eerily similar, no? Maybe Facebook was inspired by Fruit Machine (after all, we got there first), but more likely, it just shows that this is a pretty decent way to solve the problem, and great minds think alike. We're graduating to a third phase in the evolution of web best practice - from intermingling of markup, style and behaviour, through a phase in which those concerns became ever more separated and encapsulated, and finally to a model where we can do that separation at a component level. Developments like Web Components show the direction the web community is moving, and frameworks like React and Fruit Machine are in fact not a lot more than polyfills for that promised behaviour to come.
|
||||
>
|
||||
> [Read the full article...](http://labs.ft.com/2013/10/client-side-layout-engines-react-vs-fruitmachine/)
|
||||
|
||||
Even though we weren't inspired by FruitMachine (React has been used in production since before FruitMachine was open sourced), it's great to see similar technologies emerging and becoming popular.
|
||||
|
||||
## React Brunch
|
||||
|
||||
[Matthew McCray](http://elucidata.net/) implemented [react-brunch](https://npmjs.org/package/react-brunch), a JSX compilation step for [Brunch](http://brunch.io/).
|
||||
|
||||
> Adds React support to brunch by automatically compiling `*.jsx` files.
|
||||
>
|
||||
> You can configure react-brunch to automatically insert a react header (`/** @jsx React.DOM */`) into all `*.jsx` files. Disabled by default.
|
||||
>
|
||||
> Install the plugin via npm with `npm install --save react-brunch`.
|
||||
>
|
||||
> [Read more...](https://npmjs.org/package/react-brunch)
|
||||
|
||||
## Random Tweet
|
||||
|
||||
I'm going to start adding a tweet at the end of each round-up. We'll start with this one:
|
||||
|
||||
<blockquote class="twitter-tweet"><p>This weekend <a href="https://twitter.com/search?q=%23angular&src=hash">#angular</a> died for me. Meet new king <a href="https://twitter.com/search?q=%23reactjs&src=hash">#reactjs</a></p>— Eldar Djafarov ッ (@edjafarov) <a href="https://twitter.com/edjafarov/statuses/397033796710961152">November 3, 2013</a></blockquote>
|
||||
@@ -1,92 +0,0 @@
|
||||
---
|
||||
title: "Community Round-up #11"
|
||||
layout: post
|
||||
author: Vjeux
|
||||
---
|
||||
|
||||
This round-up is the proof that React has taken off from its Facebook's root: it features three in-depth presentations of React done by external people. This is awesome, keep them coming!
|
||||
|
||||
## Super VanJS 2013 Talk
|
||||
|
||||
[Steve Luscher](https://github.com/steveluscher) working at [LeanPub](https://leanpub.com/) made a 30 min talk at [Super VanJS](https://twitter.com/vanjs). He does a remarkable job at explaining why React is so fast with very exciting demos using the HTML5 Audio API.
|
||||
|
||||
<figure><iframe width="600" height="338" src="//www.youtube.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe></figure>
|
||||
|
||||
|
||||
## React Tips
|
||||
|
||||
[Connor McSheffrey](http://connormcsheffrey.com/) and [Cheng Lou](https://github.com/chenglou) added a new section to the documentation. It's a list of small tips that you will probably find useful while working on React. Since each article is very small and focused, we [encourage you to contribute](http://facebook.github.io/react/tips/introduction.html)!
|
||||
|
||||
- [Inline Styles](http://facebook.github.io/react/tips/inline-styles.html)
|
||||
- [If-Else in JSX](http://facebook.github.io/react/tips/if-else-in-JSX.html)
|
||||
- [Self-Closing Tag](http://facebook.github.io/react/tips/self-closing-tag.html)
|
||||
- [Maximum Number of JSX Root Nodes](http://facebook.github.io/react/tips/maximum-number-of-jsx-root-nodes.html)
|
||||
- [Shorthand for Specifying Pixel Values in style props](http://facebook.github.io/react/tips/style-props-value-px.html)
|
||||
- [Type of the Children props](http://facebook.github.io/react/tips/children-props-type.html)
|
||||
- [Value of null for Controlled Input](http://facebook.github.io/react/tips/controlled-input-null-value.html)
|
||||
- [`componentWillReceiveProps` Not Triggered After Mounting](http://facebook.github.io/react/tips/componentWillReceiveProps-not-triggered-after-mounting.html)
|
||||
- [Props in getInitialState Is an Anti-Pattern](http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html)
|
||||
- [DOM Event Listeners in a Component](http://facebook.github.io/react/tips/dom-event-listeners.html)
|
||||
- [Load Initial Data via AJAX](http://facebook.github.io/react/tips/initial-ajax.html)
|
||||
- [False in JSX](http://facebook.github.io/react/tips/false-in-jsx.html)
|
||||
|
||||
|
||||
## Intro to the React Framework
|
||||
|
||||
[Pavan Podila](http://blog.pixelingene.com/) wrote an in-depth introduction to React on TutsPlus. This is definitively worth reading.
|
||||
|
||||
> Within a component-tree, data should always flow down. A parent-component should set the props of a child-component to pass any data from the parent to the child. This is termed as the Owner-Owned pair. On the other hand user-events (mouse, keyboard, touches) will always bubble up from the child all the way to the root component, unless handled in between.
|
||||
<figure>[](http://dev.tutsplus.com/tutorials/intro-to-the-react-framework--net-35660)</figure>
|
||||
>
|
||||
> [Read the full article ...](http://dev.tutsplus.com/tutorials/intro-to-the-react-framework--net-35660)
|
||||
|
||||
|
||||
## 140-characters textarea
|
||||
|
||||
[Brian Kim](https://github.com/brainkim) wrote a small textarea component that gradually turns red as you reach the 140-characters limit. Because he only changes the background color, React is smart enough not to mess with the text selection.
|
||||
|
||||
<p data-height="178" data-theme-id="0" data-slug-hash="FECGb" data-user="brainkim" data-default-tab="result" class='codepen'>See the Pen <a href='http://codepen.io/brainkim/pen/FECGb'>FECGb</a> by Brian Kim (<a href='http://codepen.io/brainkim'>@brainkim</a>) on <a href='http://codepen.io'>CodePen</a></p>
|
||||
<script async src="//codepen.io/assets/embed/ei.js"></script>
|
||||
|
||||
|
||||
## Genesis Skeleton
|
||||
|
||||
[Eric Clemmons](http://ericclemmons.github.io/) is working on a "Modern, opinionated, full-stack starter kit for rapid, streamlined application development". The version 0.4.0 has just been released and has first-class support for React.
|
||||
<figure>[](http://genesis-skeleton.com/)</figure>
|
||||
|
||||
|
||||
## AgFlow Talk
|
||||
|
||||
[Robert Zaremba](http://rz.scale-it.pl/) working on [AgFlow](http://www.agflow.com/) recently talked in Poland about React.
|
||||
|
||||
> In a nutshell, I presented why we chose React among other available options (ember.js, angular, backbone ...) in AgFlow, where I’m leading an application development.
|
||||
>
|
||||
> During the talk a wanted to highlight that React is not about implementing a Model, but a way to construct visible components with some state. React is simple. It is super simple, you can learn it in 1h. On the other hand what is model? Which functionality it should provide? React does one thing and does it the best (for me)!
|
||||
>
|
||||
> [Read the full article...](http://rz.scale-it.pl/2013/10/20/frontend_components_in_react.html)
|
||||
|
||||
<figure><iframe src="https://docs.google.com/presentation/d/1JSFbjCuuexwOHCeHWBMNRIJdyfD2Z0ZQwX65WOWkfaI/embed?start=false" frameborder="0" width="600" height="468" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"> </iframe></figure>
|
||||
|
||||
|
||||
## JSX
|
||||
|
||||
[Todd Kennedy](http://tck.io/) working at Condé Nast wrote [JSXHint](https://github.com/CondeNast/JSXHint) and explains in a blog post his perspective on JSX.
|
||||
|
||||
> Lets start with the elephant in the room: JSX?
|
||||
> Is this some sort of template language? Specifically no. This might have been the first big stumbling block. What looks like to be a templating language is actually an in-line DSL that gets transpiled directly into JavaScript by the JSX transpiler.
|
||||
>
|
||||
> Creating elements in memory is quick -- copying those elements into the DOM is where the slowness occurs. This is due to a variety of issues, most namely reflow/paint. Changing the items in the DOM causes the browser to re-paint the display, apply styles, etc. We want to keep those operations to an absolute minimum, especially if we're dealing with something that needs to update the DOM frequently.
|
||||
>
|
||||
> [Read the full article...](http://tck.io/posts/jsxhint_and_react.html)
|
||||
|
||||
|
||||
## Photo Gallery
|
||||
|
||||
[Maykel Loomans](http://miekd.com/), designer at Instagram, wrote a gallery for photos he shot using React.
|
||||
<figure>[](http://photos.miekd.com/xoxo2013/)</figure>
|
||||
|
||||
|
||||
## Random Tweet
|
||||
|
||||
<img src="/react/img/blog/steve_reverse.gif" style="float: right;" />
|
||||
<div style="width: 320px;"><blockquote class="twitter-tweet"><p>I think this reversed gif of Steve Urkel best describes my changing emotions towards the React Lib <a href="http://t.co/JoX0XqSXX3">http://t.co/JoX0XqSXX3</a></p>— Ryan Seddon (@ryanseddon) <a href="https://twitter.com/ryanseddon/statuses/398572848802852864">November 7, 2013</a></blockquote></div>
|
||||
@@ -20,12 +20,12 @@ sectionid: blog
|
||||
|
||||
<div class="pagination">
|
||||
{% if paginator.previous_page %}
|
||||
<a href="/react/{{ paginator.previous_page_path }}" class="previous">
|
||||
<a href="/react/blog/{{ paginator.previous_page_path }}" class="previous">
|
||||
« Previous Page
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if paginator.next_page %}
|
||||
<a href="/react{{ paginator.next_page_path }}" class="next">
|
||||
<a href="/react/blog/{{ paginator.next_page_path }}" class="next">
|
||||
Next Page »
|
||||
</a>
|
||||
{% endif %}
|
||||
|
||||
@@ -157,6 +157,19 @@ It's easy to add comments within your JSX; they're just JS expressions:
|
||||
var content = <Container>{/* this is a comment */}<Nav /></Container>;
|
||||
```
|
||||
|
||||
## Tooling
|
||||
|
||||
Beyond the compilation step, JSX does not require any special tools.
|
||||
|
||||
* Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
|
||||
* JSX syntax highlighting is available for Sublime Text and other editors
|
||||
that support `*.tmLanguage` using the third-party
|
||||
[`JavaScript (JSX).tmLanguage`][1].
|
||||
* Linting provides accurate line numbers after compiling without sourcemaps.
|
||||
* Elements use standard scoping so linters can find usage of out-of-scope
|
||||
components.
|
||||
|
||||
[1]: https://github.com/yungsters/sublime/blob/master/tmLanguage/JavaScript%20(JSX).tmLanguage
|
||||
|
||||
## Prior Work
|
||||
|
||||
|
||||
@@ -9,9 +9,6 @@ next: interactivity-and-dynamic-uis.html
|
||||
|
||||
JSX looks like HTML but there are some important differences you may run into.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> For DOM differences, such as the inline `style` attribute, check [here](dom-differences.html).
|
||||
|
||||
## Whitespace Removal
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ With React you simply pass your event handler as a camelCased prop similar to ho
|
||||
If you'd like to use React on a touch device (i.e. a phone or tablet), simply call `React.initializeTouchEvents(true);` to turn them on.
|
||||
|
||||
|
||||
## Under the Hood: Autobinding and Event Delegation
|
||||
## Under the Hood: autoBind and Event Delegation
|
||||
|
||||
Under the hood React does a few things to keep your code performant and easy to understand.
|
||||
|
||||
|
||||
@@ -130,18 +130,3 @@ For HTML, this easily allows developers to supply multiline values. However, sin
|
||||
```
|
||||
|
||||
If you *do* decide to use children, they will behave like `defaultValue`.
|
||||
|
||||
|
||||
### Why Select Value?
|
||||
|
||||
The selected `<option>` in an HTML `<select>` is normally specified through that option's `selected` attribute. In React, in order to make components easier to manipulate, the following format is adopted instead:
|
||||
|
||||
```javascript
|
||||
<select value="B">
|
||||
<option value="A">Apple</option>
|
||||
<option value="B">Banana</option>
|
||||
<option value="C">Cranberry</option>
|
||||
</select>
|
||||
```
|
||||
|
||||
To make an uncontrolled component, `defaultValue` is used instead.
|
||||
|
||||
@@ -4,7 +4,7 @@ title: Tooling Integration
|
||||
layout: docs
|
||||
permalink: tooling-integration.html
|
||||
prev: more-about-refs.html
|
||||
next: addons.html
|
||||
next: examples.html
|
||||
---
|
||||
|
||||
Every project uses a different system for building and deploying JavaScript. We've tried to make React as environment-agnostic as possible.
|
||||
@@ -47,14 +47,6 @@ The open-source community has built tools that integrate JSX with several build
|
||||
* [react-rails](https://github.com/facebook/react-rails) - use JSX with [Ruby on Rails](http://rubyonrails.org/)
|
||||
|
||||
|
||||
### 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`.
|
||||
* Linting provides accurate line numbers after compiling without sourcemaps.
|
||||
* Elements use standard scoping so linters can find usage of out-of-scope components.
|
||||
|
||||
## React Page
|
||||
|
||||
To get started on a new project, you can use [react-page](https://github.com/facebook/react-page/), a complete React project creator. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
id: addons
|
||||
title: Add-ons
|
||||
layout: docs
|
||||
permalink: addons.html
|
||||
prev: tooling-integration.html
|
||||
next: animation.html
|
||||
---
|
||||
|
||||
`React.addons` is where we park some useful utilities for building React apps. **These should be considered experimental** but will eventually be rolled into core or a blessed utilities library:
|
||||
|
||||
- `ReactTransitions`, for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal.
|
||||
- `ReactLink`, to simplify the coordination between user's form input data and and the component's state.
|
||||
- `classSet`, for manipulating the DOM `class` string a bit more cleanly.
|
||||
|
||||
To get the add-ons, use `react-with-addons.js` (and its minified counterpart) rather than the common `react.js`.
|
||||
@@ -3,14 +3,14 @@ id: examples
|
||||
title: Examples
|
||||
layout: docs
|
||||
permalink: examples.html
|
||||
prev: addons.html
|
||||
prev: tooling-integration.html
|
||||
---
|
||||
|
||||
### Production Apps
|
||||
|
||||
* All of [Instagram.com](http://instagram.com/) is built on React.
|
||||
* Many components on [Facebook.com](http://www.facebook.com/), including the commenting interface, ads creation flows, and page insights.
|
||||
* [Khan Academy](http://khanacademy.org/) is using React for most new JS development.
|
||||
* [Khan Academy](http://khanacademy.org/) is using React for its question editor.
|
||||
|
||||
|
||||
### Sample Code
|
||||
@@ -1,99 +0,0 @@
|
||||
---
|
||||
id: animation
|
||||
title: Animation
|
||||
layout: docs
|
||||
permalink: animation.html
|
||||
prev: addons.html
|
||||
next: two-way-binding-helpers.html
|
||||
---
|
||||
|
||||
`ReactTransitions` is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM. It's inspired by the excellent [ng-animate](http://www.nganimate.org/) library.
|
||||
|
||||
## Getting Started
|
||||
|
||||
`ReactTransitionGroup` 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}
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var ReactTransitionGroup = React.addons.TransitionGroup;
|
||||
|
||||
var TodoList = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {items: ['hello', 'world', 'click', 'me']};
|
||||
},
|
||||
handleAdd: function() {
|
||||
var newItems =
|
||||
this.state.items.concat([prompt('Enter some text')]);
|
||||
this.setState({items: newItems});
|
||||
},
|
||||
handleRemove: function(i) {
|
||||
var newItems = this.state.items;
|
||||
newItems.splice(i, 1)
|
||||
this.setState({items: newItems});
|
||||
},
|
||||
render: function() {
|
||||
var items = this.state.items.map(function(item, i) {
|
||||
return (
|
||||
<div key={i} onClick={this.handleRemove.bind(this, i)}>
|
||||
{item}
|
||||
</div>
|
||||
);
|
||||
}.bind(this));
|
||||
return (
|
||||
<div>
|
||||
<div><button onClick={this.handleAdd} /></div>
|
||||
<ReactTransitionGroup transitionName="example">
|
||||
{items}
|
||||
</ReactTransitionGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
In this component, when a new item is added to `ReactTransitionGroup` it will get the `example-enter` CSS class and the `example-enter-active` CSS class added in the next tick. This is a convention based on the `transitionName` prop.
|
||||
|
||||
You can use these classes to trigger a CSS animation or transition. For example, try adding this CSS and adding a new list item:
|
||||
|
||||
```css
|
||||
.example-enter {
|
||||
opacity: 0.01;
|
||||
transition: opacity .5s ease-in;
|
||||
}
|
||||
|
||||
.example-enter.example-enter-active {
|
||||
opacity: 1;
|
||||
}
|
||||
```
|
||||
|
||||
You'll notice that when you try to remove an item `ReactTransitionGroup` keeps it in the DOM. If you're using an unminified build of React with add-ons you'll see a warning that React was expecting an animation or transition to occur. That's because `ReactTransitionGroup` keeps your DOM elements on the page until the animation completes. Try adding this CSS:
|
||||
|
||||
```css
|
||||
.example-leave {
|
||||
opacity: 1;
|
||||
transition: opacity .5s ease-in;
|
||||
}
|
||||
|
||||
.example-leave.example-leave-active {
|
||||
opacity: 0.01;
|
||||
}
|
||||
```
|
||||
|
||||
## Disabling Animations
|
||||
|
||||
You can disable animating `enter` or `leave` animations if you want. For example, sometimes you may want an `enter` animation and no `leave` animation, but `ReactTransitionGroup` waits for an animation to complete before removing your DOM node. You can add `transitionEnter={false}` or `transitionLeave={false}` props to `ReactTransitionGroup` to disable these animations.
|
||||
|
||||
## Rendering a Different Component
|
||||
|
||||
By default `ReactTransitionGroup` renders as a `span`. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`:
|
||||
|
||||
```javascript{3}
|
||||
<ReactTransitionGroup
|
||||
transitionName="example"
|
||||
component={React.DOM.ul}>
|
||||
...
|
||||
</ReactTransitionGroup>
|
||||
```
|
||||
|
||||
Every DOM component is under `React.DOM`. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself!
|
||||
@@ -1,117 +0,0 @@
|
||||
---
|
||||
id: two-way-binding-helpers
|
||||
title: Two-Way Binding Helpers
|
||||
layout: docs
|
||||
permalink: two-way-binding-helpers.html
|
||||
prev: animation.html
|
||||
next: class-name-manipulation.html
|
||||
---
|
||||
|
||||
`ReactLink` is an easy way to express two-way binding with React.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> If you're new to the framework, note that `ReactLink` is not needed for most applications and should be used cautiously.
|
||||
|
||||
In React, data flows one way: from owner to child. This is because data only flows one direction in [the Von Neumann model of computing](http://en.wikipedia.org/wiki/Von_Neumann_architecture). You can think of it as "one-way data binding."
|
||||
|
||||
However, there are lots of applications that require you to read some data and flow it back into your program. For example, when developing forms, you'll often want to update some React `state` when you receive user input. Or perhaps you want to perform layout in JavaScript and react to changes in some DOM element size.
|
||||
|
||||
In React, you would implement this by listening to a "change" event, read from your data source (usually the DOM) and call `setState()` on one of your components. "Closing the data flow loop" explicitly leads to more understandable and easier-to-maintain programs. See [our forms documentation](./forms.html) for more information.
|
||||
|
||||
Two-way binding -- implicitly enforcing that some value in the DOM is always consistent with some React `state` -- is concise and supports a wide variety of applications. We've provided `ReactLink`: syntactic sugar for setting up the common data flow loop pattern described above, or "linking" some data source to React `state`.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> ReactLink is just a thin wrapper and convention around the `onChange`/`setState()` pattern. It doesn't fundamentally change how data flows in your React application.
|
||||
|
||||
## ReactLink: Before and After
|
||||
|
||||
Here's a simple form example without using `ReactLink`:
|
||||
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var NoLink = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {value: 'Hello!'};
|
||||
},
|
||||
handleChange: function(event) {
|
||||
this.setState({value: event.target.value});
|
||||
},
|
||||
render: function() {
|
||||
var value = this.state.value;
|
||||
return <input type="text" value={value} onChange={this.handleChange} />;
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
This works really well and it's very clear how data is flowing, however with a lot of form fields it could get a bit verbose. Let's use `ReactLink` to save us some typing:
|
||||
|
||||
```javascript{4,9}
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var WithLink = React.createClass({
|
||||
mixins: [React.addons.LinkedStateMixin],
|
||||
getInitialState: function() {
|
||||
return {value: 'Hello!'};
|
||||
},
|
||||
render: function() {
|
||||
return <input type="text" valueLink={this.linkState('value')} />;
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
`LinkedStateMixin` adds a method ot your React component called `linkState()`. `linkState()` returns a `ReactLink` object which contains the current value of the React state and a callback to change it.
|
||||
|
||||
`ReactLink` objects can be passed up and down the tree as props, so it's easy (and explicit) to set up two-way binding between a component deep in the hierarchy and state that lives higher in the hierarchy.
|
||||
|
||||
## Under the Hood
|
||||
|
||||
There are two sides to `ReactLink`: the place where you create the `ReactLink` instance and the place where you use it. To prove how simple `ReactLink` is, let's rewrite each side separately to be more explicit.
|
||||
|
||||
### ReactLink Without LinkedStateMixin
|
||||
|
||||
```javascript{7-9,11-14}
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var WithoutMixin = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {value: 'Hello!'};
|
||||
},
|
||||
handleChange: function(newValue) {
|
||||
this.setState({value: newValue});
|
||||
},
|
||||
render: function() {
|
||||
var valueLink = {
|
||||
value: this.state.value,
|
||||
requestChange: this.handleChange
|
||||
};
|
||||
return <input type="text" valueLink={valueLink} />;
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
As you can see, `ReactLink` objects are very simple objects that just have a `value` and `requestChange` prop. And `LinkedStateMixin` is similarly simple: it just populates those fields with a value from `this.state` and a callback that calls `this.setState()`.
|
||||
|
||||
### ReactLink Without valueLink
|
||||
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var WithoutLink = React.createClass({
|
||||
mixins: [React.addons.LinkedStateMixin],
|
||||
getInitialState: function() {
|
||||
return {value: 'Hello!'};
|
||||
},
|
||||
render: function() {
|
||||
var valueLink = this.linkState('value');
|
||||
var handleChange = function(e) {
|
||||
valueLink.requestChange(e.target.value);
|
||||
};
|
||||
return <input type="text" value={valueLink.value} onChange={handleChange} />;
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
The `valueLink` prop is also quite simple. It simply handles the `onChange` event and calls `this.props.valueLink.requestChange()` and also uses `this.props.valueLink.value` instead of `this.props.value`. That's it!
|
||||
@@ -1,46 +0,0 @@
|
||||
---
|
||||
id: class-name-manipulation
|
||||
title: Class Name Manipulation
|
||||
layout: docs
|
||||
permalink: class-name-manipulation.html
|
||||
prev: two-way-binding-helpers.html
|
||||
next: examples.html
|
||||
---
|
||||
|
||||
`classSet()` is a neat utility for easily manipulating the DOM `class` string.
|
||||
|
||||
Here's a common scenario and its solution without `classSet()`:
|
||||
|
||||
```javascript
|
||||
// inside some `<Message />` React component
|
||||
render: function() {
|
||||
var classString = 'message';
|
||||
if (this.props.isImportant) {
|
||||
classString += ' message-important';
|
||||
}
|
||||
if (this.props.isRead) {
|
||||
classString += ' message-read';
|
||||
}
|
||||
// 'message message-important message-read'
|
||||
return <div className={classString}>Great, I'll be there.</div>;
|
||||
}
|
||||
```
|
||||
|
||||
This can quickly get tedious, as assigning class name strings can be hard to read and error-prone. `classSet()` solves this problem:
|
||||
|
||||
```javascript
|
||||
render: function() {
|
||||
var cx = React.addons.classSet;
|
||||
var classes = cx({
|
||||
'message': true,
|
||||
'message-important': this.props.isImportant,
|
||||
'message-read': this.props.isRead
|
||||
});
|
||||
// same final string, but much cleaner
|
||||
return <div className={classes}>Great, I'll be there.</div>;
|
||||
}
|
||||
```
|
||||
|
||||
When using `classSet()`, pass an object with keys of the CSS class names you might or might not need. Truthy values will result in the key being a part of the resulting string.
|
||||
|
||||
No more hacky string concatenations!
|
||||
96
docs/docs/OUTLINE.md
Normal file
@@ -0,0 +1,96 @@
|
||||
---
|
||||
id: OUTLINE
|
||||
title: Goals of the documentation
|
||||
layout: docs
|
||||
prev: 09.1-tutorial.html
|
||||
---
|
||||
- Flow of docs should mimic progression of questions a new user would ask
|
||||
- High information density -- assume the reader is adept at JS
|
||||
- Talk about best practices
|
||||
- JSFiddles for all code samples
|
||||
- Provide background for some of the design decisions
|
||||
- Less words less words less words!
|
||||
|
||||
## Outline
|
||||
|
||||
Motivation / Why React?
|
||||
- Declarative (simple)
|
||||
- Components (separation of concerns)
|
||||
- Give it 5 minutes
|
||||
|
||||
Displaying data
|
||||
- Hello world example
|
||||
- Reactive updates
|
||||
- Components are just functions
|
||||
- JSX syntax (link to separate doc?)
|
||||
- JSX gotchas
|
||||
|
||||
Interactivity and dynamic UIs
|
||||
- Click handler example
|
||||
- Event handlers / synthetic events (link to w3c docs)
|
||||
- Under the hood: autoBind and event delegation (IE8 notes)
|
||||
- React is a state machine
|
||||
- How state works
|
||||
- What components should have state?
|
||||
- What should go in state?
|
||||
- What shouldn't go in state?
|
||||
|
||||
Scaling up: using multiple components
|
||||
- Motivation: separate concerns
|
||||
- Composition example
|
||||
- Ownership (and owner vs. parent)
|
||||
- Children
|
||||
- Data flow (one-way data binding)
|
||||
- A note on performance
|
||||
|
||||
Building effective reusable components
|
||||
- You should build a reusable component library (CSS, testing etc)
|
||||
- Prop validation
|
||||
- Transferring props: a shortcut
|
||||
- Mixins
|
||||
- Testing
|
||||
|
||||
Forms
|
||||
|
||||
Working with the browser
|
||||
- The mock DOM
|
||||
- Refs / getDOMNode()
|
||||
- More about refs
|
||||
- Component lifecycle
|
||||
- Browser support and polyfills
|
||||
|
||||
Working with your environment
|
||||
- CDN-hosted React
|
||||
- Using master
|
||||
- In-browser JSX transform
|
||||
- Productionizing: precompiled JSX
|
||||
- Helpful open-source projects
|
||||
|
||||
Integrating with other UI libraries
|
||||
- Using jQuery plugins
|
||||
- Letting jQuery manage React components
|
||||
- Using with Backbone.View
|
||||
- CoffeeScript
|
||||
- Moving from Handlebars to React: an example
|
||||
|
||||
Server / static rendering
|
||||
- Motivation
|
||||
- Simple example
|
||||
- How does it work? (No DOM)
|
||||
- Rendr + React
|
||||
|
||||
Big ideas
|
||||
- Animation
|
||||
- Bootstrap bindings (responsive grids)
|
||||
- Reactive CSS
|
||||
- Web workers
|
||||
- Native views
|
||||
|
||||
Case studies
|
||||
- Comment box tutorial from scratch
|
||||
- From HTML mock to application: React one-hour email
|
||||
- Jordan's LikeToggler example
|
||||
|
||||
Reference
|
||||
- API
|
||||
- DOM differences
|
||||
@@ -53,18 +53,14 @@ If the React component was previously rendered into `container`, this will perfo
|
||||
If the optional callback is provided, it will be executed after the component is rendered or updated.
|
||||
|
||||
|
||||
### React.unmountComponentAtNode
|
||||
### React.unmountAndReleaseReactRootNode
|
||||
|
||||
```javascript
|
||||
unmountComponentAtNode(DOMElement container)
|
||||
unmountAndReleaseReactRootNode(DOMElement container)
|
||||
```
|
||||
|
||||
Remove a mounted React component from the DOM and clean up its event handlers and state.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> This method was called `React.unmountAndReleaseReactRootNode` until v0.5. It still works in v0.5 but will be removed in future versions.
|
||||
|
||||
|
||||
### React.renderComponentToString
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ var Avatar = React.createClass({
|
||||
}
|
||||
});
|
||||
|
||||
// <Avatar userId={17} width={200} height={200} />
|
||||
// <AvatarImage userId={17} width={200} height={200} />
|
||||
```
|
||||
|
||||
Properties that are specified directly on the target component instance (such as `src` and `userId` in the above example) will not be overwritten by `transferPropsTo`.
|
||||
|
||||
@@ -31,7 +31,7 @@ The `render()` function should be *pure*, meaning that it does not modify compon
|
||||
object getInitialState()
|
||||
```
|
||||
|
||||
Invoked once before the component is mounted. The return value will be used as the initial value of `this.state`.
|
||||
Invoked once when the component is mounted. The return value will be used as the initial value of `this.state`.
|
||||
|
||||
|
||||
### getDefaultProps
|
||||
|
||||
@@ -20,11 +20,11 @@ The following elements are supported:
|
||||
a abbr address area article aside audio b base bdi bdo big blockquote body br
|
||||
button canvas caption cite code col colgroup data datalist dd del details dfn
|
||||
div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6
|
||||
head header hr html i iframe img input ins kbd keygen label legend li link main
|
||||
map mark menu menuitem meta meter nav noscript object ol optgroup option output
|
||||
p param pre progress q rp rt ruby s samp script section select small source
|
||||
span strong style sub summary sup table tbody td textarea tfoot th thead time
|
||||
title tr track u ul var video wbr
|
||||
head header hr html i iframe img input ins kbd keygen label legend li link
|
||||
main map mark menu menuitem meta meter nav noscript object ol optgroup option
|
||||
output p param pre progress q rp rt ruby s samp script section select small
|
||||
source span strong style sub summary sup table tbody td textarea tfoot th
|
||||
thead time title tr track u ul var video wbr
|
||||
```
|
||||
|
||||
### SVG elements
|
||||
@@ -36,23 +36,20 @@ circle g line path polyline rect svg text
|
||||
|
||||
## Supported Attributes
|
||||
|
||||
React supports all `data-*` and `aria-*` attributes as well as every attribute in the following lists.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> All attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
|
||||
React supports all `data-*` and `aria-*` attributes as well as every attribute
|
||||
in the following lists. Note that all attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
|
||||
|
||||
For a list of events, see [Supported Events](events.html).
|
||||
|
||||
### HTML Attributes
|
||||
|
||||
```
|
||||
accept accessKey action allowFullScreen allowTransparency alt autoCapitalize
|
||||
accessKey accept action ajaxify allowFullScreen allowTransparency alt
|
||||
autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked
|
||||
className colSpan content contentEditable contextMenu controls data dateTime
|
||||
dir disabled draggable encType form frameBorder height hidden href htmlFor
|
||||
httpEquiv icon id label lang list max maxLength method min multiple name
|
||||
pattern placeholder poster preload radioGroup readOnly rel required role
|
||||
pattern poster preload placeholder radioGroup rel readOnly required role
|
||||
rowSpan scrollLeft scrollTop selected size spellCheck src step style tabIndex
|
||||
target title type value width wmode
|
||||
```
|
||||
@@ -62,7 +59,7 @@ In addition, the non-standard `autoCapitalize` attribute is supported for Mobile
|
||||
### SVG Attributes
|
||||
|
||||
```
|
||||
cx cy d fill fx fy gradientTransform gradientUnits offset points r rx ry
|
||||
spreadMethod stopColor stopOpacity stroke strokeLinecap strokeWidth transform
|
||||
version viewBox x1 x2 x y1 y2 y
|
||||
cx cy d fill fx fy points r stroke strokeLinecap strokeWidth transform x x1 x2
|
||||
version viewBox y y1 y2 spreadMethod offset stopColor stopOpacity
|
||||
gradientUnits gradientTransform
|
||||
```
|
||||
|
||||
@@ -128,6 +128,25 @@ boolean shiftKey
|
||||
```
|
||||
|
||||
|
||||
### Mutation Events
|
||||
|
||||
Event names:
|
||||
|
||||
```
|
||||
onDOMCharacterDataModified
|
||||
```
|
||||
|
||||
Properties:
|
||||
|
||||
```javascript
|
||||
Number attrChange
|
||||
String attrName
|
||||
String newValue
|
||||
String prevValue
|
||||
Node relatedNode
|
||||
```
|
||||
|
||||
|
||||
### Touch events
|
||||
|
||||
To enable touch events, call `React.initializeTouchEvents(true)` before
|
||||
|
||||
@@ -65,7 +65,7 @@ Let's build the `CommentBox` component, which is just a simple `<div>`:
|
||||
var CommentBox = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
Hello, world! I am a CommentBox.
|
||||
</div>
|
||||
);
|
||||
@@ -120,7 +120,7 @@ Let's build skeletons for `CommentList` and `CommentForm` which will, again, be
|
||||
var CommentList = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentList">
|
||||
<div class="commentList">
|
||||
Hello, world! I am a CommentList.
|
||||
</div>
|
||||
);
|
||||
@@ -130,7 +130,7 @@ var CommentList = React.createClass({
|
||||
var CommentForm = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentForm">
|
||||
<div class="commentForm">
|
||||
Hello, world! I am a CommentForm.
|
||||
</div>
|
||||
);
|
||||
@@ -145,7 +145,7 @@ Next, update the `CommentBox` component to use its new friends:
|
||||
var CommentBox = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList />
|
||||
<CommentForm />
|
||||
@@ -166,7 +166,7 @@ Let's create our third component, `Comment`. We will want to pass it the author
|
||||
var CommentList = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentList">
|
||||
<div class="commentList">
|
||||
<Comment author="Pete Hunt">This is one comment</Comment>
|
||||
<Comment author="Jordan Walke">This is *another* comment</Comment>
|
||||
</div>
|
||||
@@ -186,8 +186,8 @@ Let's create the Comment component. It will read the data passed to it from the
|
||||
var Comment = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div className="comment">
|
||||
<h2 className="commentAuthor">
|
||||
<div class="comment">
|
||||
<h2 class="commentAuthor">
|
||||
{this.props.author}
|
||||
</h2>
|
||||
{this.props.children}
|
||||
@@ -223,8 +223,8 @@ var converter = new Showdown.converter();
|
||||
var Comment = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div className="comment">
|
||||
<h2 className="commentAuthor">
|
||||
<div class="comment">
|
||||
<h2 class="commentAuthor">
|
||||
{this.props.author}
|
||||
</h2>
|
||||
{converter.makeHtml(this.props.children.toString())}
|
||||
@@ -247,8 +247,8 @@ var Comment = React.createClass({
|
||||
render: function() {
|
||||
var rawMarkup = converter.makeHtml(this.props.children.toString());
|
||||
return (
|
||||
<div className="comment">
|
||||
<h2 className="commentAuthor">
|
||||
<div class="comment">
|
||||
<h2 class="commentAuthor">
|
||||
{this.props.author}
|
||||
</h2>
|
||||
<span dangerouslySetInnerHTML={{"{{"}}__html: rawMarkup}} />
|
||||
@@ -281,7 +281,7 @@ We need to get this data into `CommentList` in a modular way. Modify `CommentBox
|
||||
var CommentBox = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.props.data} />
|
||||
<CommentForm />
|
||||
@@ -306,7 +306,7 @@ var CommentList = React.createClass({
|
||||
return <Comment author={comment.author}>{comment.text}</Comment>;
|
||||
});
|
||||
return (
|
||||
<div className="commentList">
|
||||
<div class="commentList">
|
||||
{commentNodes}
|
||||
</div>
|
||||
);
|
||||
@@ -346,7 +346,7 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm />
|
||||
@@ -369,7 +369,7 @@ When the component is first created, we want to GET some JSON from the server an
|
||||
]
|
||||
```
|
||||
|
||||
We will use jQuery to help make an asynchronous request to the server.
|
||||
We will use jQuery 1.5 to help make an asynchronous request to the server.
|
||||
|
||||
Note: because this is becoming an AJAX application you'll need to develop your app using a web server rather than as a file sitting on your file system. The easiest way to do this is to run `python -m SimpleHTTPServer` in your application's directory.
|
||||
|
||||
@@ -379,6 +379,8 @@ var CommentBox = React.createClass({
|
||||
getInitialState: function() {
|
||||
$.ajax({
|
||||
url: 'comments.json',
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -387,7 +389,7 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm />
|
||||
@@ -405,6 +407,8 @@ var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -415,11 +419,14 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
componentWillMount: function() {
|
||||
this.loadCommentsFromServer();
|
||||
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
|
||||
setInterval(
|
||||
this.loadCommentsFromServer.bind(this),
|
||||
this.props.pollInterval
|
||||
);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm />
|
||||
@@ -429,13 +436,13 @@ var CommentBox = React.createClass({
|
||||
});
|
||||
|
||||
React.renderComponent(
|
||||
<CommentBox url="comments.json" pollInterval={2000} />,
|
||||
<CommentBox url="comments.json" pollInterval={5000} />,
|
||||
document.getElementById('content')
|
||||
);
|
||||
|
||||
```
|
||||
|
||||
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 2 seconds after that. Try running this in your browser and changing the `comments.json` file; within 2 seconds, the changes will show!
|
||||
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 5 seconds after that. Try running this in your browser and changing the `comments.json` file; within 5 seconds, the changes will show!
|
||||
|
||||
### Adding new comments
|
||||
|
||||
@@ -446,10 +453,10 @@ Now it's time to build the form. Our `CommentForm` component should ask the user
|
||||
var CommentForm = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<form className="commentForm">
|
||||
<form class="commentForm">
|
||||
<input type="text" placeholder="Your name" />
|
||||
<input type="text" placeholder="Say something..." />
|
||||
<input type="submit" value="Post" />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -474,14 +481,14 @@ var CommentForm = React.createClass({
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<form className="commentForm" onSubmit={this.handleSubmit}>
|
||||
<form class="commentForm" onSubmit={this.handleSubmit}>
|
||||
<input type="text" placeholder="Your name" ref="author" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Say something..."
|
||||
ref="text"
|
||||
/>
|
||||
<input type="submit" value="Post" />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -510,6 +517,8 @@ var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -523,11 +532,14 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
componentWillMount: function() {
|
||||
this.loadCommentsFromServer();
|
||||
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
|
||||
setInterval(
|
||||
this.loadCommentsFromServer.bind(this),
|
||||
this.props.pollInterval
|
||||
);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
@@ -554,14 +566,14 @@ var CommentForm = React.createClass({
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<form className="commentForm" onSubmit={this.handleSubmit}>
|
||||
<form class="commentForm" onSubmit={this.handleSubmit}>
|
||||
<input type="text" placeholder="Your name" ref="author" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Say something..."
|
||||
ref="text"
|
||||
/>
|
||||
<input type="submit" value="Post" />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -576,6 +588,8 @@ var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -584,8 +598,9 @@ var CommentBox = React.createClass({
|
||||
handleCommentSubmit: function(comment) {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
type: 'POST',
|
||||
data: comment,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -596,11 +611,14 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
componentWillMount: function() {
|
||||
this.loadCommentsFromServer();
|
||||
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
|
||||
setInterval(
|
||||
this.loadCommentsFromServer.bind(this),
|
||||
this.props.pollInterval
|
||||
);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
@@ -622,6 +640,8 @@ var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -629,12 +649,13 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
handleCommentSubmit: function(comment) {
|
||||
var comments = this.state.data;
|
||||
var newComments = comments.concat([comment]);
|
||||
this.setState({data: newComments});
|
||||
comments.push(comment);
|
||||
this.setState({data: comments});
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
type: 'POST',
|
||||
data: comment,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -645,11 +666,14 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
componentWillMount: function() {
|
||||
this.loadCommentsFromServer();
|
||||
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
|
||||
setInterval(
|
||||
this.loadCommentsFromServer.bind(this),
|
||||
this.props.pollInterval
|
||||
);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div className="commentBox">
|
||||
<div class="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
|
||||
@@ -28,20 +28,6 @@ The uncompressed, development version of React core with inline documentation.
|
||||
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
|
||||
```
|
||||
|
||||
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.min.js">React With Add-Ons {{site.react_version}} (production)</a>
|
||||
The compressed, production version of React with [add-ons](/react/docs/addons.html).
|
||||
|
||||
```html
|
||||
<script src="http://fb.me/react-with-addons-{{site.react_version}}.min.js"></script>
|
||||
```
|
||||
|
||||
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.js">React With Add-Ons {{site.react_version}} (development)</a>
|
||||
The uncompressed, development version of React with [add-ons](/react/docs/addons.html).
|
||||
|
||||
```html
|
||||
<script src="http://fb.me/react-with-addons-{{site.react_version}}.js"></script>
|
||||
```
|
||||
|
||||
#### <a href="http://fb.me/JSXTransformer-{{site.react_version}}.js">JSX Transform</a>
|
||||
The JSX transformer used to support [XML syntax](/react/docs/jsx-in-depth.html) in JavaScript.
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 168 KiB |
|
Before Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 5.4 MiB |
|
Before Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 53 KiB |
|
Before Width: | Height: | Size: 246 KiB |
@@ -7,25 +7,23 @@ id: home
|
||||
<section class="light home-section">
|
||||
<div class="marketing-row">
|
||||
<div class="marketing-col">
|
||||
<h3>Just the UI</h3>
|
||||
<h3>Declarative</h3>
|
||||
<p>
|
||||
Lots of people use React as the V in MVC.
|
||||
Since React makes no assumptions about the rest of your technology stack,
|
||||
it's easy to try it out on a small feature in an existing project.
|
||||
React uses a declarative paradigm that makes it easier to reason about
|
||||
your application.
|
||||
</p>
|
||||
</div>
|
||||
<div class="marketing-col">
|
||||
<h3>Virtual DOM</h3>
|
||||
<h3>Efficient</h3>
|
||||
<p>
|
||||
React uses a <i>virtual DOM</i> diff implementation for ultra-high performance. It can also
|
||||
render on the server using Node.js — no heavy browser DOM required.
|
||||
React computes the minimal set of changes necessary to keep your DOM
|
||||
up-to-date.
|
||||
</p>
|
||||
</div>
|
||||
<div class="marketing-col">
|
||||
<h3>Data flow</h3>
|
||||
<h3>Flexible</h3>
|
||||
<p>
|
||||
React implements one-way reactive data flow which reduces boilerplate and is
|
||||
easier to reason about than traditional data binding.
|
||||
React works with the libraries and frameworks that you already know.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -62,7 +60,7 @@ id: home
|
||||
This example uses `state` to track the current list of items as well as
|
||||
the text that the user has entered. Although event handlers appear to be
|
||||
rendered inline, they will be collected and implemented using event
|
||||
delegation.
|
||||
delegation.
|
||||
</p>
|
||||
<div id="todoExample"></div>
|
||||
</div>
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
---
|
||||
id: introduction
|
||||
title: Introduction
|
||||
layout: tips
|
||||
permalink: introduction.html
|
||||
next: inline-styles.html
|
||||
---
|
||||
|
||||
The React tips section provides bite-sized information that can answer lots of questions you might have and warn you against common pitfalls.
|
||||
|
||||
## Contributing
|
||||
|
||||
Submit a pull request to the [React repository](https://github.com/facebook/react) following the [current tips](https://github.com/facebook/react/tree/master/docs) entries' style. If you have a recipe that needs review prior to submitting a PR you can find help in the [#reactjs channel on freenode](irc://chat.freenode.net/reactjs) or the [reactjs Google group](http://groups.google.com/group/reactjs). Also, check the [Tips Wiki](https://github.com/facebook/react/wiki/Tips-(Previously-Cookbook)) for entries in-progress and general guidelines on writing React tips.
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
id: inline-styles
|
||||
title: Inline Styles
|
||||
layout: tips
|
||||
permalink: inline-styles.html
|
||||
next: if-else-in-JSX.html
|
||||
prev: introduction.html
|
||||
---
|
||||
|
||||
In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string ([more on that later](/react/tips/style-props-value-px.html)):
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var divStyle = {
|
||||
color: 'white',
|
||||
backgroundImage: 'url(' + imgUrl + ')',
|
||||
WebkitTransition: 'all' // note the capital 'W' here
|
||||
};
|
||||
|
||||
React.renderComponent(<div style={divStyle}>Hello World!</div>, mountNode);
|
||||
```
|
||||
|
||||
Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. `node.style.backgroundImage`). Vendor prefixes should begin with a capital letter. This is why `WebkitTransition` has an uppercase "W".
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
id: if-else-in-JSX
|
||||
title: If-Else in JSX
|
||||
layout: tips
|
||||
permalink: if-else-in-JSX.html
|
||||
prev: inline-styles.html
|
||||
next: self-closing-tag.html
|
||||
---
|
||||
|
||||
`if-else` statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. Take this basic example:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
// This JSX:
|
||||
React.renderComponent(<div id="msg">Hello World!</div>, mountNode);
|
||||
|
||||
// Is transformed to this JS:
|
||||
React.renderComponent(React.DOM.div({id:"msg"}, "Hello World!"), mountNode);
|
||||
```
|
||||
|
||||
This means that `if` statements don't fit in. Take this example:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
// This JSX:
|
||||
<div id={if (condition) { 'msg' }}>Hello World!</div>
|
||||
|
||||
// Is transformed to this JS:
|
||||
React.DOM.div({id: if (condition) { 'msg' }}, "Hello World!");
|
||||
```
|
||||
|
||||
That's not valid JS. You probably want to make use of a ternary expression:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
React.renderComponent(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
|
||||
```
|
||||
|
||||
Try using it today with the [JSX compiler](/react/jsx-compiler.html).
|
||||
@@ -1,14 +0,0 @@
|
||||
---
|
||||
id: self-closing-tag
|
||||
title: Self-Closing Tag
|
||||
layout: tips
|
||||
permalink: self-closing-tag.html
|
||||
prev: if-else-in-JSX.html
|
||||
next: maximum-number-of-jsx-root-nodes.html
|
||||
---
|
||||
|
||||
In JSX, `<MyComponent />` alone is valid while `<MyComponent>` isn't. All tags must be closed, either with the self-closing format or with a corresponding closing tag (`</MyComponent>`).
|
||||
|
||||
> Note:
|
||||
>
|
||||
> Every React component can be self-closing: `<div />`. `<div></div>` is also an equivalent.
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
id: maximum-number-of-jsx-root-nodes
|
||||
title: Maximum Number of JSX Root Nodes
|
||||
layout: tips
|
||||
permalink: maximum-number-of-jsx-root-nodes.html
|
||||
prev: self-closing-tag.html
|
||||
next: style-props-value-px.html
|
||||
---
|
||||
|
||||
Currently, in a component's `render`, you can only return one node; if you have, say, a list of `div`s to return, you must wrap your components within a `div`, `span` or any other component.
|
||||
|
||||
Don't forget that JSX compiles into regular js; returning two functions doesn't really make syntactic sense. Likewise, don't put more than one child in a ternary.
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
id: style-props-value-px
|
||||
title: Shorthand for Specifying Pixel Values in style props
|
||||
layout: tips
|
||||
permalink: style-props-value-px.html
|
||||
prev: maximum-number-of-jsx-root-nodes.html
|
||||
next: children-props-type.html
|
||||
---
|
||||
|
||||
When specifying a pixel value for your inline `style` prop, React automatically appends the string "px" for you after your number value, so this works:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var divStyle = {height: 10}; // rendered as "height:10px"
|
||||
React.renderComponent(<div style={divStyle}>Hello World!</div>, mountNode);
|
||||
```
|
||||
|
||||
See [Inline Styles](/react/tips/inline-styles.html) for more info.
|
||||
|
||||
Sometimes you _do_ want to keep the CSS properties unitless. Here's a list of properties that won't get the automatic "px" suffix:
|
||||
|
||||
- `fillOpacity`
|
||||
- `fontWeight`
|
||||
- `lineHeight`
|
||||
- `opacity`
|
||||
- `orphans`
|
||||
- `zIndex`
|
||||
- `zoom`
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
id: children-props-type
|
||||
title: Type of the Children props
|
||||
layout: tips
|
||||
permalink: children-props-type.html
|
||||
prev: style-props-value-px.html
|
||||
next: controlled-input-null-value.html
|
||||
---
|
||||
|
||||
Usually, a component's children (`this.props.children`) is an array of components:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var GenericWrapper = React.createClass({
|
||||
componentDidMount: function() {
|
||||
console.log(Array.isArray(this.props.children)); // => true
|
||||
},
|
||||
render: function() {
|
||||
return <div />;
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(
|
||||
<GenericWrapper><span/><span/><span/></GenericWrapper>,
|
||||
mountNode
|
||||
);
|
||||
```
|
||||
|
||||
However, when there is only a single child, `this.props.children` will be the single child component itself _without the array wrapper_. This saves an array allocation.
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var GenericWrapper = React.createClass({
|
||||
componentDidMount: function() {
|
||||
console.log(Array.isArray(this.props.children)); // => false
|
||||
|
||||
// warning: yields 5 for length of the string 'hello', not 1 for the
|
||||
// length of the non-existant array wrapper!
|
||||
console.log(this.props.children.length);
|
||||
},
|
||||
render: function() {
|
||||
return <div />;
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<GenericWrapper>hello</GenericWrapper>, mountNode);
|
||||
```
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
id: controlled-input-null-value
|
||||
title: Value of null for Controlled Input
|
||||
layout: tips
|
||||
permalink: controlled-input-null-value.html
|
||||
prev: children-props-type.html
|
||||
next: componentWillReceiveProps-not-triggered-after-mounting.html
|
||||
---
|
||||
|
||||
Specifying the `value` prop on a [controlled component](/react/docs/forms.html) prevents the user from changing the input unless you desire so.
|
||||
|
||||
You might have run into a problem where `value` is specified, but the input can still be changed without consent. In this case, you might have accidentally set `value` to `undefined` or `null`.
|
||||
|
||||
The snippet below shows this phenomenon; after a second, the text becomes editable.
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
React.renderComponent(<input value="hi" />, mountNode);
|
||||
|
||||
setTimeout(function() {
|
||||
React.renderComponent(<input value={null} />, mountNode);
|
||||
}, 2000);
|
||||
```
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
id: componentWillReceiveProps-not-triggered-after-mounting
|
||||
title: componentWillReceiveProps Not Triggered After Mounting
|
||||
layout: tips
|
||||
permalink: componentWillReceiveProps-not-triggered-after-mounting.html
|
||||
prev: controlled-input-null-value.html
|
||||
next: props-in-getInitialState-as-anti-pattern.html
|
||||
---
|
||||
|
||||
`componentWillReceiveProps` isn't triggered after the node is put on scene. This is by design. Check out [other lifecycle methods](/react/docs/component-specs.html) for the one that suits your needs.
|
||||
|
||||
The reason for that is because `componentWillReceiveProps` often handles the logic of comparing with the old props and acting upon changes; not triggering it at mounting (where there are no old props) helps in defining what the method does.
|
||||
@@ -1,62 +0,0 @@
|
||||
---
|
||||
id: props-in-getInitialState-as-anti-pattern
|
||||
title: Props in getInitialState Is an Anti-Pattern
|
||||
layout: tips
|
||||
permalink: props-in-getInitialState-as-anti-pattern.html
|
||||
prev: componentWillReceiveProps-not-triggered-after-mounting.html
|
||||
next: dom-event-listeners.html
|
||||
---
|
||||
|
||||
> Note:
|
||||
>
|
||||
> This isn't really a React-specific tip, as such anti-patterns often occur in code in general; in this case, React simply points them out more clearly.
|
||||
|
||||
Using props, passed down from parent, to generate state in `getInitialState` often leads to duplication of "source of truth", i.e. where the real data is. Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.
|
||||
|
||||
Bad example:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var MessageBox = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {nameWithQualifier: "Mr. " + this.props.name};
|
||||
},
|
||||
render: function() {
|
||||
return <div>{this.state.nameWithQualifier}</div>;
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
|
||||
```
|
||||
|
||||
Better:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var MessageBox = React.createClass({
|
||||
render: function() {
|
||||
return <div>{"Mr. " + this.props.name}</div>;
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
|
||||
```
|
||||
|
||||
For more complex logic:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var MessageBox = React.createClass({
|
||||
render: function() {
|
||||
return <div>{this.getNameWithQualifier(this.props.name)}</div>;
|
||||
},
|
||||
getNameWithQualifier: function(name) {
|
||||
return 'Mr. ' + name;
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
|
||||
```
|
||||
@@ -1,46 +0,0 @@
|
||||
---
|
||||
id: dom-event-listeners
|
||||
title: DOM Event Listeners in a Component
|
||||
layout: tips
|
||||
permalink: dom-event-listeners.html
|
||||
prev: props-in-getInitialState-as-anti-pattern.html
|
||||
next: initial-ajax.html
|
||||
---
|
||||
|
||||
> Note:
|
||||
>
|
||||
> This entry shows how to attach DOM events not provided by React ([check here for more info](/react/docs/events.html)). This is good for integrations with other libraries such as jQuery.
|
||||
|
||||
Try to resize the window:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var Box = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {windowWidth: window.innerWidth};
|
||||
},
|
||||
|
||||
handleResize: function(e) {
|
||||
this.setState({windowWidth: window.innerWidth});
|
||||
},
|
||||
|
||||
componentDidMount: function() {
|
||||
window.addEventListener('resize', this.handleResize);
|
||||
},
|
||||
|
||||
componentWillUnmount: function() {
|
||||
window.removeEventListener('resize', this.handleResize);
|
||||
},
|
||||
|
||||
render: function() {
|
||||
return <div>Current window width: {this.state.windowWidth}</div>;
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<Box />, mountNode);
|
||||
```
|
||||
|
||||
`componentDidMount` is called after the component is mounted and has a DOM representation. This is often a place where you would attach generic DOM events.
|
||||
|
||||
Notice that the event callback is bound to the react component and not the original element. React automatically binds methods to the current component instance for you through a process of [autobinding](../docs/interactivity-and-dynamic-uis.html#under-the-hood-autobinding-and-event-delegation).
|
||||
@@ -1,47 +0,0 @@
|
||||
---
|
||||
id: initial-ajax
|
||||
title: Load Initial Data via AJAX
|
||||
layout: tips
|
||||
permalink: initial-ajax.html
|
||||
prev: dom-event-listeners.html
|
||||
next: false-in-jsx.html
|
||||
---
|
||||
|
||||
Fetch data in `componentDidMount`. When the response arrives, store the data in state, triggering a render to update your UI.
|
||||
|
||||
This example fetches the desired Github user's latest gist:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var UserGist = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {
|
||||
username: '',
|
||||
lastGistUrl: ''
|
||||
};
|
||||
},
|
||||
componentDidMount: function() {
|
||||
$.get(this.props.source, function(result) {
|
||||
var lastGist = result[0];
|
||||
this.setState({
|
||||
username: lastGist.user.login,
|
||||
lastGistUrl: lastGist.html_url
|
||||
});
|
||||
}.bind(this));
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div>
|
||||
{this.state.username}'s last gist is
|
||||
<a href={this.state.lastGistUrl}>here</a>.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(
|
||||
<UserGist source="https://api.github.com/users/octocat/gists" />,
|
||||
mountNode
|
||||
);
|
||||
```
|
||||
@@ -1,33 +0,0 @@
|
||||
---
|
||||
id: false-in-jsx
|
||||
title: False in JSX
|
||||
layout: tips
|
||||
permalink: false-in-jsx.html
|
||||
prev: initial-ajax.html
|
||||
next: communicate-between-components.html
|
||||
---
|
||||
|
||||
Here's how `false` renders in different contexts:
|
||||
|
||||
Renders as `id="false"`:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
React.renderComponent(<div id={false} />, mountNode);
|
||||
```
|
||||
|
||||
String "false" as input value:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
React.renderComponent(<input value={false} />, mountNode);
|
||||
```
|
||||
|
||||
No child:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
React.renderComponent(<div>{false}</div>, mountNode);
|
||||
```
|
||||
|
||||
The reason why this one doesn't render as the string `"false"` as a `div` child is to allow the more common use-case: `<div>{x > 1 && 'You have more than one item'}</div>`.
|
||||
@@ -1,40 +0,0 @@
|
||||
---
|
||||
id: communicate-between-components
|
||||
title: Communicate Between Components
|
||||
layout: tips
|
||||
permalink: communicate-between-components.html
|
||||
prev: false-in-jsx.html
|
||||
---
|
||||
|
||||
For parent-child communication, simply [pass props](/react/docs/multiple-components.html).
|
||||
|
||||
For child-parent communication:
|
||||
Say your `GroceryList` component has a list of items generated through an array. When a list item is clicked, you want to display its name:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var GroceryList = React.createClass({
|
||||
handleClick: function(i) {
|
||||
console.log('You clicked: ' + this.props.items[i]);
|
||||
},
|
||||
|
||||
render: function() {
|
||||
return (
|
||||
<div>
|
||||
{this.props.items.map(function(item, i) {
|
||||
return (
|
||||
<div onClick={this.handleClick.bind(this, i)} key={i}>{item}</div>
|
||||
);
|
||||
}, this)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(
|
||||
<GroceryList items={['Apple', 'Banana', 'Cranberry']} />, mountNode
|
||||
);
|
||||
```
|
||||
|
||||
Notice the use of `bind(this, arg1, arg2, ...)`: we're simply passing more arguments to `handleClick`. This is not a new React concept; it's just JavaScript.
|
||||
@@ -1,3 +0,0 @@
|
||||
# TodoMVC-Backbone
|
||||
|
||||
This is a lightweight version of TodoMVC. Its primary purpose is to demo the Backbone integration rather than being feature-complete (refer to `todomvc-director` for a full TodoMVC-compilant app).
|
||||
@@ -34,7 +34,7 @@ body {
|
||||
font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#todoapp {
|
||||
.todoapp {
|
||||
background: #fff;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
margin: 130px 0 40px 0;
|
||||
@@ -46,7 +46,7 @@ body {
|
||||
0 25px 50px 0 rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
#todoapp:before {
|
||||
.todoapp:before {
|
||||
content: '';
|
||||
border-left: 1px solid #f5d6d6;
|
||||
border-right: 1px solid #f5d6d6;
|
||||
@@ -57,16 +57,16 @@ body {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
#todoapp input::-webkit-input-placeholder {
|
||||
.todoapp input::-webkit-input-placeholder {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
#todoapp input::-moz-placeholder {
|
||||
.todoapp input:-moz-placeholder {
|
||||
font-style: italic;
|
||||
color: #a9a9a9;
|
||||
}
|
||||
|
||||
#todoapp h1 {
|
||||
.todoapp h1 {
|
||||
position: absolute;
|
||||
top: -120px;
|
||||
width: 100%;
|
||||
@@ -83,12 +83,12 @@ body {
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
#header {
|
||||
.header {
|
||||
padding-top: 15px;
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
#header:before {
|
||||
.header:before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
@@ -109,7 +109,7 @@ body {
|
||||
border-top-right-radius: 1px;
|
||||
}
|
||||
|
||||
#new-todo,
|
||||
.new-todo,
|
||||
.edit {
|
||||
position: relative;
|
||||
margin: 0;
|
||||
@@ -135,7 +135,7 @@ body {
|
||||
font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#new-todo {
|
||||
.new-todo {
|
||||
padding: 16px 16px 16px 60px;
|
||||
border: none;
|
||||
background: rgba(0, 0, 0, 0.02);
|
||||
@@ -143,17 +143,17 @@ body {
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
#main {
|
||||
.main {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
border-top: 1px dotted #adadad;
|
||||
}
|
||||
|
||||
label[for='toggle-all'] {
|
||||
.toggle-all-label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#toggle-all {
|
||||
.toggle-all {
|
||||
position: absolute;
|
||||
top: -42px;
|
||||
left: -4px;
|
||||
@@ -162,50 +162,50 @@ label[for='toggle-all'] {
|
||||
border: none; /* Mobile Safari */
|
||||
}
|
||||
|
||||
#toggle-all:before {
|
||||
.toggle-all:before {
|
||||
content: '»';
|
||||
font-size: 28px;
|
||||
color: #d9d9d9;
|
||||
padding: 0 25px 7px;
|
||||
}
|
||||
|
||||
#toggle-all:checked:before {
|
||||
.toggle-all:checked:before {
|
||||
color: #737373;
|
||||
}
|
||||
|
||||
#todo-list {
|
||||
.todo-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
#todo-list li {
|
||||
.todo-list li {
|
||||
position: relative;
|
||||
font-size: 24px;
|
||||
border-bottom: 1px dotted #ccc;
|
||||
}
|
||||
|
||||
#todo-list li:last-child {
|
||||
.todo-list li:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
#todo-list li.editing {
|
||||
.todo-list li.editing {
|
||||
border-bottom: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
#todo-list li.editing .edit {
|
||||
.todo-list li.editing .edit {
|
||||
display: block;
|
||||
width: 506px;
|
||||
padding: 13px 17px 12px 17px;
|
||||
margin: 0 0 0 43px;
|
||||
}
|
||||
|
||||
#todo-list li.editing .view {
|
||||
.todo-list li.editing .view {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#todo-list li .toggle {
|
||||
.todo-list li .toggle {
|
||||
text-align: center;
|
||||
width: 40px;
|
||||
/* auto, since non-WebKit browsers doesn't support input styling */
|
||||
@@ -222,7 +222,7 @@ label[for='toggle-all'] {
|
||||
appearance: none;
|
||||
}
|
||||
|
||||
#todo-list li .toggle:after {
|
||||
.todo-list li .toggle:after {
|
||||
content: '✔';
|
||||
line-height: 43px; /* 40 + a couple of pixels visual adjustment */
|
||||
font-size: 20px;
|
||||
@@ -230,17 +230,16 @@ label[for='toggle-all'] {
|
||||
text-shadow: 0 -1px 0 #bfbfbf;
|
||||
}
|
||||
|
||||
#todo-list li .toggle:checked:after {
|
||||
.todo-list li .toggle:checked:after {
|
||||
color: #85ada7;
|
||||
text-shadow: 0 1px 0 #669991;
|
||||
bottom: 1px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
#todo-list li label {
|
||||
white-space: pre;
|
||||
.todo-list li label {
|
||||
word-break: break-word;
|
||||
padding: 15px 60px 15px 15px;
|
||||
padding: 15px;
|
||||
margin-left: 45px;
|
||||
display: block;
|
||||
line-height: 1.2;
|
||||
@@ -251,12 +250,12 @@ label[for='toggle-all'] {
|
||||
transition: color 0.4s;
|
||||
}
|
||||
|
||||
#todo-list li.completed label {
|
||||
.todo-list li.completed label {
|
||||
color: #a9a9a9;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
#todo-list li .destroy {
|
||||
.todo-list li .destroy {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
@@ -274,7 +273,7 @@ label[for='toggle-all'] {
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
#todo-list li .destroy:hover {
|
||||
.todo-list li .destroy:hover {
|
||||
text-shadow: 0 0 1px #000,
|
||||
0 0 10px rgba(199, 107, 107, 0.8);
|
||||
-webkit-transform: scale(1.3);
|
||||
@@ -284,23 +283,23 @@ label[for='toggle-all'] {
|
||||
transform: scale(1.3);
|
||||
}
|
||||
|
||||
#todo-list li .destroy:after {
|
||||
.todo-list li .destroy:after {
|
||||
content: '✖';
|
||||
}
|
||||
|
||||
#todo-list li:hover .destroy {
|
||||
.todo-list li:hover .destroy {
|
||||
display: block;
|
||||
}
|
||||
|
||||
#todo-list li .edit {
|
||||
.todo-list li .edit {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#todo-list li.editing:last-child {
|
||||
.todo-list li.editing:last-child {
|
||||
margin-bottom: -1px;
|
||||
}
|
||||
|
||||
#footer {
|
||||
.footer {
|
||||
color: #777;
|
||||
padding: 0 15px;
|
||||
position: absolute;
|
||||
@@ -312,7 +311,7 @@ label[for='toggle-all'] {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#footer:before {
|
||||
.footer:before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
@@ -327,12 +326,12 @@ label[for='toggle-all'] {
|
||||
0 44px 2px -6px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
#todo-count {
|
||||
.todo-count {
|
||||
float: left;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
#filters {
|
||||
.filters {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
@@ -341,21 +340,21 @@ label[for='toggle-all'] {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
#filters li {
|
||||
.filters li {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
#filters li a {
|
||||
.filters li a {
|
||||
color: #83756f;
|
||||
margin: 2px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#filters li a.selected {
|
||||
.filters li a.selected {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#clear-completed {
|
||||
.clear-completed {
|
||||
float: right;
|
||||
position: relative;
|
||||
line-height: 20px;
|
||||
@@ -367,12 +366,12 @@ label[for='toggle-all'] {
|
||||
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
#clear-completed:hover {
|
||||
.clear-completed:hover {
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
#info {
|
||||
.info {
|
||||
margin: 65px auto 0;
|
||||
color: #a6a6a6;
|
||||
font-size: 12px;
|
||||
@@ -380,25 +379,29 @@ label[for='toggle-all'] {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#info a {
|
||||
.info a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.submitButton {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/*
|
||||
Hack to remove background from Mobile Safari.
|
||||
Can't use it globally since it destroys checkboxes in Firefox and Opera
|
||||
*/
|
||||
@media screen and (-webkit-min-device-pixel-ratio:0) {
|
||||
#toggle-all,
|
||||
#todo-list li .toggle {
|
||||
.toggle-all,
|
||||
.todo-list li .toggle {
|
||||
background: none;
|
||||
}
|
||||
|
||||
#todo-list li .toggle {
|
||||
.todo-list li .toggle {
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
#toggle-all {
|
||||
.toggle-all {
|
||||
top: -56px;
|
||||
left: -15px;
|
||||
width: 65px;
|
||||
@@ -410,147 +413,6 @@ label[for='toggle-all'] {
|
||||
}
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
hr {
|
||||
margin: 20px 0;
|
||||
border: 0;
|
||||
border-top: 1px dashed #C5C5C5;
|
||||
border-bottom: 1px dashed #F7F7F7;
|
||||
}
|
||||
|
||||
.learn a {
|
||||
font-weight: normal;
|
||||
text-decoration: none;
|
||||
color: #b83f45;
|
||||
}
|
||||
|
||||
.learn a:hover {
|
||||
text-decoration: underline;
|
||||
color: #787e7e;
|
||||
}
|
||||
|
||||
.learn h3,
|
||||
.learn h4,
|
||||
.learn h5 {
|
||||
margin: 10px 0;
|
||||
font-weight: 500;
|
||||
line-height: 1.2;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.learn h3 {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.learn h4 {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.learn h5 {
|
||||
margin-bottom: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.learn ul {
|
||||
padding: 0;
|
||||
margin: 0 0 30px 25px;
|
||||
}
|
||||
|
||||
.learn li {
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.learn p {
|
||||
font-size: 15px;
|
||||
font-weight: 300;
|
||||
line-height: 1.3;
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.quote {
|
||||
border: none;
|
||||
margin: 20px 0 60px 0;
|
||||
}
|
||||
|
||||
.quote p {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.quote p:before {
|
||||
content: '“';
|
||||
font-size: 50px;
|
||||
opacity: .15;
|
||||
position: absolute;
|
||||
top: -20px;
|
||||
left: 3px;
|
||||
}
|
||||
|
||||
.quote p:after {
|
||||
content: '”';
|
||||
font-size: 50px;
|
||||
opacity: .15;
|
||||
position: absolute;
|
||||
bottom: -42px;
|
||||
right: 3px;
|
||||
}
|
||||
|
||||
.quote footer {
|
||||
position: absolute;
|
||||
bottom: -40px;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.quote footer img {
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.quote footer a {
|
||||
margin-left: 5px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.speech-bubble {
|
||||
position: relative;
|
||||
padding: 10px;
|
||||
background: rgba(0, 0, 0, .04);
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.speech-bubble:after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
right: 30px;
|
||||
border: 13px solid transparent;
|
||||
border-top-color: rgba(0, 0, 0, .04);
|
||||
}
|
||||
|
||||
/**body*/.learn-bar > .learn {
|
||||
position: absolute;
|
||||
width: 272px;
|
||||
top: 8px;
|
||||
left: -300px;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
background-color: rgba(255, 255, 255, .6);
|
||||
transition-property: left;
|
||||
transition-duration: 500ms;
|
||||
}
|
||||
|
||||
@media (min-width: 899px) {
|
||||
/**body*/.learn-bar {
|
||||
width: auto;
|
||||
margin: 0 0 0 300px;
|
||||
}
|
||||
/**body*/.learn-bar > .learn {
|
||||
left: 8px;
|
||||
}
|
||||
/**body*/.learn-bar #todoapp {
|
||||
width: 550px;
|
||||
margin: 130px auto 40px auto;
|
||||
}
|
||||
.hidden{
|
||||
display:none;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<![endif]-->
|
||||
</head>
|
||||
<body>
|
||||
<div id="container"></div>
|
||||
<div id="todoapp"></div>
|
||||
<script src="../../build/react.js"></script>
|
||||
<script src="../../build/JSXTransformer.js"></script>
|
||||
<script type="text/javascript" src="../shared/thirdparty/jquery.min.js" charset="utf-8"></script>
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
/** @jsx React.DOM */
|
||||
|
||||
function cx(obj) {
|
||||
var s = '';
|
||||
for (var key in obj) {
|
||||
if (!obj.hasOwnProperty(key)) {
|
||||
continue;
|
||||
}
|
||||
if (obj[key]) {
|
||||
s += key + ' ';
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
var Todo = Backbone.Model.extend({
|
||||
|
||||
// Default attributes for the todo
|
||||
// and ensure that each todo created has `title` and `completed` keys.
|
||||
defaults: {
|
||||
@@ -14,6 +28,7 @@ var Todo = Backbone.Model.extend({
|
||||
completed: !this.get('completed')
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
var TodoList = Backbone.Collection.extend({
|
||||
@@ -53,19 +68,6 @@ var TodoList = Backbone.Collection.extend({
|
||||
var Utils = {
|
||||
pluralize: function( count, word ) {
|
||||
return count === 1 ? word : word + 's';
|
||||
},
|
||||
|
||||
stringifyObjKeys: function(obj) {
|
||||
var s = '';
|
||||
for (var key in obj) {
|
||||
if (!obj.hasOwnProperty(key)) {
|
||||
continue;
|
||||
}
|
||||
if (obj[key]) {
|
||||
s += key + ' ';
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -73,47 +75,31 @@ var Utils = {
|
||||
|
||||
var TodoItem = React.createClass({
|
||||
handleSubmit: function(event) {
|
||||
var val = this.refs.editField.getDOMNode().value.trim();
|
||||
var val = this.refs.editField.getDOMNode().value;
|
||||
if (val) {
|
||||
this.props.onSave(val);
|
||||
} else {
|
||||
this.props.onDestroy();
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
onEdit: function() {
|
||||
this.props.onEdit();
|
||||
this.refs.editField.getDOMNode().focus();
|
||||
},
|
||||
|
||||
render: function() {
|
||||
var classes = Utils.stringifyObjKeys({
|
||||
completed: this.props.todo.get('completed'), editing: this.props.editing
|
||||
});
|
||||
return (
|
||||
<li className={classes}>
|
||||
<div className="view">
|
||||
<li class={cx({completed: this.props.todo.get('completed'), editing: this.props.editing})}>
|
||||
<div class="view">
|
||||
<input
|
||||
className="toggle"
|
||||
class="toggle"
|
||||
type="checkbox"
|
||||
checked={this.props.todo.get('completed')}
|
||||
checked={this.props.todo.get('completed') ? 'checked' : null}
|
||||
onChange={this.props.onToggle}
|
||||
key={this.props.key}
|
||||
/>
|
||||
<label onDoubleClick={this.onEdit}>
|
||||
{this.props.todo.get('title')}
|
||||
</label>
|
||||
<button className="destroy" onClick={this.props.onDestroy} />
|
||||
<label onDoubleClick={this.onEdit}>{this.props.todo.get('title')}</label>
|
||||
<button class="destroy" onClick={this.props.onDestroy} />
|
||||
</div>
|
||||
<form onSubmit={this.handleSubmit}>
|
||||
<input
|
||||
ref="editField"
|
||||
className="edit"
|
||||
defaultValue={this.props.todo.get('title')}
|
||||
onBlur={this.handleSubmit}
|
||||
autoFocus="autofocus"
|
||||
/>
|
||||
<input ref="editField" class="edit" value={this.props.todo.get('title')} />
|
||||
</form>
|
||||
</li>
|
||||
);
|
||||
@@ -127,46 +113,37 @@ var TodoFooter = React.createClass({
|
||||
|
||||
if (this.props.completedCount > 0) {
|
||||
clearButton = (
|
||||
<button id="clear-completed" onClick={this.props.onClearCompleted}>
|
||||
Clear completed ({this.props.completedCount})
|
||||
</button>
|
||||
<button class="clear-completed" onClick={this.props.onClearCompleted}>Clear completed ({this.props.completedCount})</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<footer id="footer">
|
||||
<span id="todo-count">
|
||||
<strong>{this.props.count}</strong>{' '}
|
||||
{activeTodoWord}{' '}left
|
||||
</span>
|
||||
<footer class="footer">
|
||||
<span class="todo-count"><strong>{this.props.count}</strong>{' '}{activeTodoWord}{' '}left</span>
|
||||
{clearButton}
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// An example generic Mixin that you can add to any component that should react
|
||||
// to changes in a Backbone component. The use cases we've identified thus far
|
||||
// are for Collections -- since they trigger a change event whenever any of
|
||||
// their constituent items are changed there's no need to reconcile for regular
|
||||
// models. One caveat: this relies on getBackboneModels() to always return the
|
||||
// same model instances throughout the lifecycle of the component. If you're
|
||||
// using this mixin correctly (it should be near the top of your component
|
||||
// hierarchy) this should not be an issue.
|
||||
// An example generic Mixin that you can add to any component that should react to changes in a Backbone component.
|
||||
// The use cases we've identified thus far are for Collections -- since they trigger a change event whenever
|
||||
// any of their constituent items are changed there's no need to reconcile for regular models.
|
||||
// One caveat: this relies on getBackboneModels() to always return the same model instances throughout the
|
||||
// lifecycle of the component. If you're using this mixin correctly (it should be near the top of your
|
||||
// component hierarchy) this should not be an issue.
|
||||
var BackboneMixin = {
|
||||
componentDidMount: function() {
|
||||
// Whenever there may be a change in the Backbone data, trigger a reconcile.
|
||||
this.getBackboneModels().forEach(function(model) {
|
||||
model.on('add change remove', this.forceUpdate.bind(this, null), this);
|
||||
}, this);
|
||||
this.getBackboneModels().map(function(model) {
|
||||
model.on('add change remove', this.forceUpdate, this);
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
componentWillUnmount: function() {
|
||||
// Ensure that we clean up any dangling references when the component is
|
||||
// destroyed.
|
||||
this.getBackboneModels().forEach(function(model) {
|
||||
// Ensure that we clean up any dangling references when the component is destroyed.
|
||||
this.getBackboneModels().map(function(model) {
|
||||
model.off(null, null, this);
|
||||
}, this);
|
||||
}.bind(this));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -175,28 +152,21 @@ var TodoApp = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {editing: null};
|
||||
},
|
||||
|
||||
componentDidMount: function() {
|
||||
// Additional functionality for todomvc: fetch() the collection on init
|
||||
this.props.todos.fetch();
|
||||
this.refs.newField.getDOMNode().focus();
|
||||
},
|
||||
|
||||
componentDidUpdate: function() {
|
||||
// If saving were expensive we'd listen for mutation events on Backbone and
|
||||
// do this manually. however, since saving isn't expensive this is an
|
||||
// elegant way to keep it reactively up-to-date.
|
||||
this.props.todos.forEach(function(todo) {
|
||||
// If saving were expensive we'd listen for mutation events on Backbone and do this manually.
|
||||
// however, since saving isn't expensive this is an elegant way to keep it reactively up-to-date.
|
||||
this.props.todos.map(function(todo) {
|
||||
todo.save();
|
||||
});
|
||||
},
|
||||
|
||||
getBackboneModels: function() {
|
||||
return [this.props.todos];
|
||||
},
|
||||
|
||||
handleSubmit: function(event) {
|
||||
event.preventDefault();
|
||||
handleSubmit: function() {
|
||||
var val = this.refs.newField.getDOMNode().value.trim();
|
||||
if (val) {
|
||||
this.props.todos.create({
|
||||
@@ -206,63 +176,48 @@ var TodoApp = React.createClass({
|
||||
});
|
||||
this.refs.newField.getDOMNode().value = '';
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
toggleAll: function(event) {
|
||||
var checked = event.nativeEvent.target.checked;
|
||||
this.props.todos.forEach(function(todo) {
|
||||
this.props.todos.map(function(todo) {
|
||||
todo.set('completed', checked);
|
||||
});
|
||||
},
|
||||
|
||||
destroy: function(todo) {
|
||||
this.props.todos.remove(todo);
|
||||
},
|
||||
edit: function(todo) {
|
||||
this.setState({editing: todo.get('id')});
|
||||
},
|
||||
|
||||
save: function(todo, text) {
|
||||
todo.set('title', text);
|
||||
this.setState({editing: null});
|
||||
},
|
||||
|
||||
clearCompleted: function() {
|
||||
this.props.todos.completed().forEach(function(todo) {
|
||||
this.props.todos.completed().map(function(todo) {
|
||||
todo.destroy();
|
||||
});
|
||||
},
|
||||
|
||||
render: function() {
|
||||
var footer = null;
|
||||
var main = null;
|
||||
var todoItems = this.props.todos.map(function(todo) {
|
||||
return (
|
||||
<TodoItem
|
||||
key={Math.random()}
|
||||
todo={todo}
|
||||
onToggle={todo.toggle.bind(todo)}
|
||||
onDestroy={todo.destroy.bind(todo)}
|
||||
onEdit={this.edit.bind(this, todo)}
|
||||
editing={this.state.editing === todo.get('id')}
|
||||
onSave={this.save.bind(this, todo)}
|
||||
/>
|
||||
);
|
||||
}, this);
|
||||
return <TodoItem todo={todo} onToggle={todo.toggle.bind(todo)} onDestroy={this.destroy.bind(this, todo)} onEdit={this.edit.bind(this, todo)} editing={this.state.editing === todo.get('id')} onSave={this.save.bind(this, todo)} />;
|
||||
}.bind(this));
|
||||
|
||||
var activeTodoCount = this.props.todos.remaining().length;
|
||||
var completedCount = todoItems.length - activeTodoCount;
|
||||
if (activeTodoCount || completedCount) {
|
||||
footer =
|
||||
<TodoFooter
|
||||
count={activeTodoCount}
|
||||
completedCount={completedCount}
|
||||
onClearCompleted={this.clearCompleted}
|
||||
/>;
|
||||
if (activeTodoCount || completedCount) {
|
||||
footer = <TodoFooter count={activeTodoCount} completedCount={completedCount} onClearCompleted={this.clearCompleted} />;
|
||||
}
|
||||
|
||||
if (todoItems.length) {
|
||||
main = (
|
||||
<section id="main">
|
||||
<input id="toggle-all" type="checkbox" onChange={this.toggleAll} />
|
||||
<ul id="todo-list">
|
||||
<section class="main">
|
||||
<input class="toggle-all" type="checkbox" onChange={this.toggleAll} />
|
||||
<label class="toggle-all-label">Mark all as complete</label>
|
||||
<ul class="todo-list">
|
||||
{todoItems}
|
||||
</ul>
|
||||
</section>
|
||||
@@ -271,33 +226,23 @@ var TodoApp = React.createClass({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<section id="todoapp">
|
||||
<header id="header">
|
||||
<section class="todoapp">
|
||||
<header class="header">
|
||||
<h1>todos</h1>
|
||||
<form onSubmit={this.handleSubmit}>
|
||||
<input
|
||||
ref="newField"
|
||||
id="new-todo"
|
||||
placeholder="What needs to be done?"
|
||||
/>
|
||||
<input ref="newField" class="new-todo" placeholder="What needs to be done?" autofocus="autofocus" />
|
||||
</form>
|
||||
</header>
|
||||
{main}
|
||||
{footer}
|
||||
</section>
|
||||
<footer id="info">
|
||||
<footer class="info">
|
||||
<p>Double-click to edit a todo</p>
|
||||
<p>
|
||||
Created by{' '}
|
||||
<a href="http://github.com/petehunt/">petehunt</a>
|
||||
</p>
|
||||
<p>Created by{' '}<a href="http://github.com/petehunt/">petehunt</a></p>
|
||||
<p>Part of{' '}<a href="http://todomvc.com">TodoMVC</a></p>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(
|
||||
<TodoApp todos={new TodoList()} />, document.getElementById('container')
|
||||
);
|
||||
React.renderComponent(<TodoApp todos={new TodoList()} />, document.getElementById('todoapp'));
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# TodoMVC-director
|
||||
|
||||
This is the exact copy of the React-powered [TodoMVC](http://todomvc.com/labs/architecture-examples/react/). To test it, use [bower](http://bower.io) to fetch the dependencies:
|
||||
|
||||
`bower install`
|
||||
|
||||
Then fire up a server here:
|
||||
|
||||
`python -m SimpleHTTPServer`
|
||||
|
||||
And go visit `localhost:8000`.
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"name": "todomvc-react",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"todomvc-common": "~0.1.7",
|
||||
"react": "~0.4.0",
|
||||
"director": "~1.2.0"
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en" data-framework="react">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>React • TodoMVC</title>
|
||||
<link rel="stylesheet" href="bower_components/todomvc-common/base.css">
|
||||
</head>
|
||||
<body>
|
||||
<section id="todoapp"></section>
|
||||
<footer id="info"></footer>
|
||||
<div id="benchmark"></div>
|
||||
|
||||
<script src="bower_components/todomvc-common/base.js"></script>
|
||||
<script src="bower_components/react/react.js"></script>
|
||||
<script src="bower_components/react/JSXTransformer.js"></script>
|
||||
<script src="bower_components/director/build/director.min.js"></script>
|
||||
|
||||
<script type="text/jsx" src="js/utils.jsx"></script>
|
||||
<script type="text/jsx" src="js/todoItem.jsx"></script>
|
||||
<script type="text/jsx" src="js/footer.jsx"></script>
|
||||
<script type="text/jsx" src="js/app.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,207 +0,0 @@
|
||||
/**
|
||||
* @jsx React.DOM
|
||||
*/
|
||||
/*jshint quotmark:false */
|
||||
/*jshint white:false */
|
||||
/*jshint trailing:false */
|
||||
/*jshint newcap:false */
|
||||
/*global Utils, ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS,
|
||||
TodoItem, TodoFooter, React, Router*/
|
||||
|
||||
(function (window, React) {
|
||||
'use strict';
|
||||
|
||||
window.ALL_TODOS = 'all';
|
||||
window.ACTIVE_TODOS = 'active';
|
||||
window.COMPLETED_TODOS = 'completed';
|
||||
|
||||
var ENTER_KEY = 13;
|
||||
|
||||
var TodoApp = React.createClass({
|
||||
getInitialState: function () {
|
||||
var todos = Utils.store('react-todos');
|
||||
return {
|
||||
todos: todos,
|
||||
nowShowing: ALL_TODOS,
|
||||
editing: null
|
||||
};
|
||||
},
|
||||
|
||||
componentDidMount: function () {
|
||||
var router = Router({
|
||||
'/': this.setState.bind(this, {nowShowing: ALL_TODOS}),
|
||||
'/active': this.setState.bind(this, {nowShowing: ACTIVE_TODOS}),
|
||||
'/completed': this.setState.bind(this, {nowShowing: COMPLETED_TODOS})
|
||||
});
|
||||
router.init();
|
||||
this.refs.newField.getDOMNode().focus();
|
||||
},
|
||||
|
||||
handleNewTodoKeyDown: function (event) {
|
||||
if (event.which !== ENTER_KEY) {
|
||||
return;
|
||||
}
|
||||
|
||||
var val = this.refs.newField.getDOMNode().value.trim();
|
||||
var todos;
|
||||
var newTodo;
|
||||
|
||||
if (val) {
|
||||
todos = this.state.todos;
|
||||
newTodo = {
|
||||
id: Utils.uuid(),
|
||||
title: val,
|
||||
completed: false
|
||||
};
|
||||
this.setState({todos: todos.concat([newTodo])});
|
||||
this.refs.newField.getDOMNode().value = '';
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
toggleAll: function (event) {
|
||||
var checked = event.target.checked;
|
||||
|
||||
this.state.todos.forEach(function (todo) {
|
||||
todo.completed = checked;
|
||||
});
|
||||
|
||||
this.setState({todos: this.state.todos});
|
||||
},
|
||||
|
||||
toggle: function (todo) {
|
||||
todo.completed = !todo.completed;
|
||||
this.setState({todos: this.state.todos});
|
||||
},
|
||||
|
||||
destroy: function (todo) {
|
||||
var newTodos = this.state.todos.filter(function (candidate) {
|
||||
return candidate.id !== todo.id;
|
||||
});
|
||||
|
||||
this.setState({todos: newTodos});
|
||||
},
|
||||
|
||||
edit: function (todo, callback) {
|
||||
// refer to todoItem.js `handleEdit` for the reasoning behind the
|
||||
// callback
|
||||
this.setState({editing: todo.id}, function () {
|
||||
callback();
|
||||
});
|
||||
},
|
||||
|
||||
save: function (todo, text) {
|
||||
todo.title = text;
|
||||
this.setState({todos: this.state.todos, editing: null});
|
||||
},
|
||||
|
||||
cancel: function () {
|
||||
this.setState({editing: null});
|
||||
},
|
||||
|
||||
clearCompleted: function () {
|
||||
var newTodos = this.state.todos.filter(function (todo) {
|
||||
return !todo.completed;
|
||||
});
|
||||
|
||||
this.setState({todos: newTodos});
|
||||
},
|
||||
|
||||
componentDidUpdate: function () {
|
||||
Utils.store('react-todos', this.state.todos);
|
||||
},
|
||||
|
||||
render: function () {
|
||||
var footer = null;
|
||||
var main = null;
|
||||
var todoItems = {};
|
||||
var activeTodoCount;
|
||||
var completedCount;
|
||||
|
||||
var shownTodos = this.state.todos.filter(function (todo) {
|
||||
switch (this.state.nowShowing) {
|
||||
case ACTIVE_TODOS:
|
||||
return !todo.completed;
|
||||
case COMPLETED_TODOS:
|
||||
return todo.completed;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
shownTodos.forEach(function (todo) {
|
||||
todoItems[todo.id] = (
|
||||
<TodoItem
|
||||
todo={todo}
|
||||
onToggle={this.toggle.bind(this, todo)}
|
||||
onDestroy={this.destroy.bind(this, todo)}
|
||||
onEdit={this.edit.bind(this, todo)}
|
||||
editing={this.state.editing === todo.id}
|
||||
onSave={this.save.bind(this, todo)}
|
||||
onCancel={this.cancel}
|
||||
/>
|
||||
);
|
||||
}.bind(this));
|
||||
|
||||
activeTodoCount = this.state.todos.filter(function (todo) {
|
||||
return !todo.completed;
|
||||
}).length;
|
||||
|
||||
completedCount = this.state.todos.length - activeTodoCount;
|
||||
|
||||
if (activeTodoCount || completedCount) {
|
||||
footer =
|
||||
<TodoFooter
|
||||
count={activeTodoCount}
|
||||
completedCount={completedCount}
|
||||
nowShowing={this.state.nowShowing}
|
||||
onClearCompleted={this.clearCompleted}
|
||||
/>;
|
||||
}
|
||||
|
||||
if (this.state.todos.length) {
|
||||
main = (
|
||||
<section id="main">
|
||||
<input
|
||||
id="toggle-all"
|
||||
type="checkbox"
|
||||
onChange={this.toggleAll}
|
||||
checked={activeTodoCount === 0}
|
||||
/>
|
||||
<ul id="todo-list">
|
||||
{todoItems}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header id="header">
|
||||
<h1>todos</h1>
|
||||
<input
|
||||
ref="newField"
|
||||
id="new-todo"
|
||||
placeholder="What needs to be done?"
|
||||
onKeyDown={this.handleNewTodoKeyDown}
|
||||
/>
|
||||
</header>
|
||||
{main}
|
||||
{footer}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<TodoApp />, document.getElementById('todoapp'));
|
||||
React.renderComponent(
|
||||
<div>
|
||||
<p>Double-click to edit a todo</p>
|
||||
<p>Created by{' '}
|
||||
<a href="http://github.com/petehunt/">petehunt</a>
|
||||
</p>
|
||||
<p>Part of{' '}<a href="http://todomvc.com">TodoMVC</a></p>
|
||||
</div>,
|
||||
document.getElementById('info'));
|
||||
})(window, React);
|
||||
@@ -1,58 +0,0 @@
|
||||
/**
|
||||
* @jsx React.DOM
|
||||
*/
|
||||
/*jshint quotmark:false */
|
||||
/*jshint white:false */
|
||||
/*jshint trailing:false */
|
||||
/*jshint newcap:false */
|
||||
/*global React, ALL_TODOS, ACTIVE_TODOS, Utils, COMPLETED_TODOS */
|
||||
(function (window) {
|
||||
'use strict';
|
||||
|
||||
window.TodoFooter = React.createClass({
|
||||
render: function () {
|
||||
var activeTodoWord = Utils.pluralize(this.props.count, 'item');
|
||||
var clearButton = null;
|
||||
|
||||
if (this.props.completedCount > 0) {
|
||||
clearButton = (
|
||||
<button
|
||||
id="clear-completed"
|
||||
onClick={this.props.onClearCompleted}>
|
||||
{''}Clear completed ({this.props.completedCount}){''}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
var show = {
|
||||
ALL_TODOS: '',
|
||||
ACTIVE_TODOS: '',
|
||||
COMPLETED_TODOS: ''
|
||||
};
|
||||
show[this.props.nowShowing] = 'selected';
|
||||
|
||||
return (
|
||||
<footer id="footer">
|
||||
<span id="todo-count">
|
||||
<strong>{this.props.count}</strong>
|
||||
{' '}{activeTodoWord}{' '}left{''}
|
||||
</span>
|
||||
<ul id="filters">
|
||||
<li>
|
||||
<a href="#/" className={show[ALL_TODOS]}>All</a>
|
||||
</li>
|
||||
{' '}
|
||||
<li>
|
||||
<a href="#/active" className={show[ACTIVE_TODOS]}>Active</a>
|
||||
</li>
|
||||
{' '}
|
||||
<li>
|
||||
<a href="#/completed" className={show[COMPLETED_TODOS]}>Completed</a>
|
||||
</li>
|
||||
</ul>
|
||||
{clearButton}
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
});
|
||||
})(window);
|
||||
@@ -1,93 +0,0 @@
|
||||
/**
|
||||
* @jsx React.DOM
|
||||
*/
|
||||
/*jshint quotmark: false */
|
||||
/*jshint white: false */
|
||||
/*jshint trailing: false */
|
||||
/*jshint newcap: false */
|
||||
/*global React, Utils */
|
||||
(function (window) {
|
||||
'use strict';
|
||||
|
||||
var ESCAPE_KEY = 27;
|
||||
var ENTER_KEY = 13;
|
||||
|
||||
window.TodoItem = React.createClass({
|
||||
handleSubmit: function () {
|
||||
var val = this.state.editText.trim();
|
||||
if (val) {
|
||||
this.props.onSave(val);
|
||||
this.setState({editText: val});
|
||||
} else {
|
||||
this.props.onDestroy();
|
||||
}
|
||||
return false;
|
||||
},
|
||||
handleEdit: function () {
|
||||
// react optimizes renders by batching them. This means you can't call
|
||||
// parent's `onEdit` (which in this case triggeres a re-render), and
|
||||
// immediately manipulate the DOM as if the rendering's over. Put it as a
|
||||
// callback. Refer to app.js' `edit` method
|
||||
this.props.onEdit(function () {
|
||||
var node = this.refs.editField.getDOMNode();
|
||||
node.focus();
|
||||
node.setSelectionRange(node.value.length, node.value.length);
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
handleKeyDown: function (event) {
|
||||
if (event.keyCode === ESCAPE_KEY) {
|
||||
this.setState({editText: this.props.todo.title});
|
||||
this.props.onCancel();
|
||||
} else if (event.keyCode === ENTER_KEY) {
|
||||
this.handleSubmit();
|
||||
} else {
|
||||
this.setState({editText: event.target.value});
|
||||
}
|
||||
},
|
||||
|
||||
handleChange: function (event) {
|
||||
this.setState({editText: event.target.value});
|
||||
},
|
||||
|
||||
getInitialState: function () {
|
||||
return {editText: this.props.todo.title};
|
||||
},
|
||||
|
||||
componentWillReceiveProps: function (nextProps) {
|
||||
if (nextProps.todo.title !== this.props.todo.title) {
|
||||
this.setState(this.getInitialState());
|
||||
}
|
||||
},
|
||||
|
||||
render: function () {
|
||||
return (
|
||||
<li className={Utils.stringifyObjKeys({
|
||||
completed: this.props.todo.completed,
|
||||
editing: this.props.editing
|
||||
})}>
|
||||
<div className="view">
|
||||
<input
|
||||
className="toggle"
|
||||
type="checkbox"
|
||||
checked={this.props.todo.completed ? 'checked' : null}
|
||||
onChange={this.props.onToggle}
|
||||
/>
|
||||
<label onDoubleClick={this.handleEdit}>
|
||||
{this.props.todo.title}
|
||||
</label>
|
||||
<button className='destroy' onClick={this.props.onDestroy} />
|
||||
</div>
|
||||
<input
|
||||
ref="editField"
|
||||
className="edit"
|
||||
value={this.state.editText}
|
||||
onBlur={this.handleSubmit}
|
||||
onChange={this.handleChange}
|
||||
onKeyDown={this.handleKeyDown}
|
||||
/>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
});
|
||||
})(window);
|
||||
@@ -1,49 +0,0 @@
|
||||
(function (window) {
|
||||
'use strict';
|
||||
|
||||
window.Utils = {
|
||||
uuid: function () {
|
||||
/*jshint bitwise:false */
|
||||
var i, random;
|
||||
var uuid = '';
|
||||
|
||||
for (i = 0; i < 32; i++) {
|
||||
random = Math.random() * 16 | 0;
|
||||
if (i === 8 || i === 12 || i === 16 || i === 20) {
|
||||
uuid += '-';
|
||||
}
|
||||
uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random))
|
||||
.toString(16);
|
||||
}
|
||||
|
||||
return uuid;
|
||||
},
|
||||
|
||||
pluralize: function (count, word) {
|
||||
return count === 1 ? word : word + 's';
|
||||
},
|
||||
|
||||
store: function (namespace, data) {
|
||||
if (data) {
|
||||
return localStorage.setItem(namespace, JSON.stringify(data));
|
||||
}
|
||||
|
||||
var store = localStorage.getItem(namespace);
|
||||
return (store && JSON.parse(store)) || [];
|
||||
},
|
||||
|
||||
stringifyObjKeys: function (obj) {
|
||||
var s = '';
|
||||
var key;
|
||||
|
||||
for (key in obj) {
|
||||
if (obj.hasOwnProperty(key) && obj[key]) {
|
||||
s += key + ' ';
|
||||
}
|
||||
}
|
||||
|
||||
return s.trim();
|
||||
}
|
||||
};
|
||||
|
||||
})(window);
|
||||
425
examples/todomvc/css/base.css
Normal file
@@ -0,0 +1,425 @@
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
button {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
font-size: 100%;
|
||||
vertical-align: baseline;
|
||||
font-family: inherit;
|
||||
color: inherit;
|
||||
-webkit-appearance: none;
|
||||
/*-moz-appearance: none;*/
|
||||
-ms-appearance: none;
|
||||
-o-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
|
||||
body {
|
||||
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
|
||||
line-height: 1.4em;
|
||||
background: #eaeaea url('bg.png');
|
||||
color: #4d4d4d;
|
||||
width: 550px;
|
||||
margin: 0 auto;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-font-smoothing: antialiased;
|
||||
-ms-font-smoothing: antialiased;
|
||||
-o-font-smoothing: antialiased;
|
||||
font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.todoapp {
|
||||
background: #fff;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
margin: 130px 0 40px 0;
|
||||
border: 1px solid #ccc;
|
||||
position: relative;
|
||||
border-top-left-radius: 2px;
|
||||
border-top-right-radius: 2px;
|
||||
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2),
|
||||
0 25px 50px 0 rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.todoapp:before {
|
||||
content: '';
|
||||
border-left: 1px solid #f5d6d6;
|
||||
border-right: 1px solid #f5d6d6;
|
||||
width: 2px;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 40px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.todoapp input::-webkit-input-placeholder {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.todoapp input:-moz-placeholder {
|
||||
font-style: italic;
|
||||
color: #a9a9a9;
|
||||
}
|
||||
|
||||
.todoapp h1 {
|
||||
position: absolute;
|
||||
top: -120px;
|
||||
width: 100%;
|
||||
font-size: 70px;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
color: #b3b3b3;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
text-shadow: -1px -1px rgba(0, 0, 0, 0.2);
|
||||
-webkit-text-rendering: optimizeLegibility;
|
||||
-moz-text-rendering: optimizeLegibility;
|
||||
-ms-text-rendering: optimizeLegibility;
|
||||
-o-text-rendering: optimizeLegibility;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding-top: 15px;
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
.header:before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
left: 0;
|
||||
height: 15px;
|
||||
z-index: 2;
|
||||
border-bottom: 1px solid #6c615c;
|
||||
background: #8d7d77;
|
||||
background: -webkit-gradient(linear, left top, left bottom, from(rgba(132, 110, 100, 0.8)),to(rgba(101, 84, 76, 0.8)));
|
||||
background: -webkit-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
|
||||
background: -moz-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
|
||||
background: -o-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
|
||||
background: -ms-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
|
||||
background: linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
|
||||
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#9d8b83', EndColorStr='#847670');
|
||||
border-top-left-radius: 1px;
|
||||
border-top-right-radius: 1px;
|
||||
}
|
||||
|
||||
.new-todo,
|
||||
.edit {
|
||||
position: relative;
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
font-size: 24px;
|
||||
font-family: inherit;
|
||||
line-height: 1.4em;
|
||||
border: 0;
|
||||
outline: none;
|
||||
color: inherit;
|
||||
padding: 6px;
|
||||
border: 1px solid #999;
|
||||
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
|
||||
-webkit-box-sizing: border-box;
|
||||
-moz-box-sizing: border-box;
|
||||
-ms-box-sizing: border-box;
|
||||
-o-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-font-smoothing: antialiased;
|
||||
-ms-font-smoothing: antialiased;
|
||||
-o-font-smoothing: antialiased;
|
||||
font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.new-todo {
|
||||
padding: 16px 16px 16px 60px;
|
||||
border: none;
|
||||
background: rgba(0, 0, 0, 0.02);
|
||||
z-index: 2;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.main {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
border-top: 1px dotted #adadad;
|
||||
}
|
||||
|
||||
.toggle-all-label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.toggle-all {
|
||||
position: absolute;
|
||||
top: -42px;
|
||||
left: -4px;
|
||||
width: 40px;
|
||||
text-align: center;
|
||||
border: none; /* Mobile Safari */
|
||||
}
|
||||
|
||||
.toggle-all:before {
|
||||
content: '»';
|
||||
font-size: 28px;
|
||||
color: #d9d9d9;
|
||||
padding: 0 25px 7px;
|
||||
}
|
||||
|
||||
.toggle-all:checked:before {
|
||||
color: #737373;
|
||||
}
|
||||
|
||||
.todo-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.todo-list li {
|
||||
position: relative;
|
||||
font-size: 24px;
|
||||
border-bottom: 1px dotted #ccc;
|
||||
}
|
||||
|
||||
.todo-list li:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.todo-list li.editing {
|
||||
border-bottom: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.todo-list li.editing .edit {
|
||||
display: block;
|
||||
width: 506px;
|
||||
padding: 13px 17px 12px 17px;
|
||||
margin: 0 0 0 43px;
|
||||
}
|
||||
|
||||
.todo-list li.editing .view {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.todo-list li .toggle {
|
||||
text-align: center;
|
||||
width: 40px;
|
||||
/* auto, since non-WebKit browsers doesn't support input styling */
|
||||
height: auto;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
margin: auto 0;
|
||||
border: none; /* Mobile Safari */
|
||||
-webkit-appearance: none;
|
||||
/*-moz-appearance: none;*/
|
||||
-ms-appearance: none;
|
||||
-o-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
|
||||
.todo-list li .toggle:after {
|
||||
content: '✔';
|
||||
line-height: 43px; /* 40 + a couple of pixels visual adjustment */
|
||||
font-size: 20px;
|
||||
color: #d9d9d9;
|
||||
text-shadow: 0 -1px 0 #bfbfbf;
|
||||
}
|
||||
|
||||
.todo-list li .toggle:checked:after {
|
||||
color: #85ada7;
|
||||
text-shadow: 0 1px 0 #669991;
|
||||
bottom: 1px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.todo-list li label {
|
||||
word-break: break-word;
|
||||
padding: 15px;
|
||||
margin-left: 45px;
|
||||
display: block;
|
||||
line-height: 1.2;
|
||||
-webkit-transition: color 0.4s;
|
||||
-moz-transition: color 0.4s;
|
||||
-ms-transition: color 0.4s;
|
||||
-o-transition: color 0.4s;
|
||||
transition: color 0.4s;
|
||||
}
|
||||
|
||||
.todo-list li.completed label {
|
||||
color: #a9a9a9;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.todo-list li .destroy {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 10px;
|
||||
bottom: 0;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
margin: auto 0;
|
||||
font-size: 22px;
|
||||
color: #a88a8a;
|
||||
-webkit-transition: all 0.2s;
|
||||
-moz-transition: all 0.2s;
|
||||
-ms-transition: all 0.2s;
|
||||
-o-transition: all 0.2s;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.todo-list li .destroy:hover {
|
||||
text-shadow: 0 0 1px #000,
|
||||
0 0 10px rgba(199, 107, 107, 0.8);
|
||||
-webkit-transform: scale(1.3);
|
||||
-moz-transform: scale(1.3);
|
||||
-ms-transform: scale(1.3);
|
||||
-o-transform: scale(1.3);
|
||||
transform: scale(1.3);
|
||||
}
|
||||
|
||||
.todo-list li .destroy:after {
|
||||
content: '✖';
|
||||
}
|
||||
|
||||
.todo-list li:hover .destroy {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.todo-list li .edit {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.todo-list li.editing:last-child {
|
||||
margin-bottom: -1px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
color: #777;
|
||||
padding: 0 15px;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: -31px;
|
||||
left: 0;
|
||||
height: 20px;
|
||||
z-index: 1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.footer:before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 31px;
|
||||
left: 0;
|
||||
height: 50px;
|
||||
z-index: -1;
|
||||
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3),
|
||||
0 6px 0 -3px rgba(255, 255, 255, 0.8),
|
||||
0 7px 1px -3px rgba(0, 0, 0, 0.3),
|
||||
0 43px 0 -6px rgba(255, 255, 255, 0.8),
|
||||
0 44px 2px -6px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.todo-count {
|
||||
float: left;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.filters {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.filters li {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.filters li a {
|
||||
color: #83756f;
|
||||
margin: 2px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.filters li a.selected {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.clear-completed {
|
||||
float: right;
|
||||
position: relative;
|
||||
line-height: 20px;
|
||||
text-decoration: none;
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
font-size: 11px;
|
||||
padding: 0 10px;
|
||||
border-radius: 3px;
|
||||
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.clear-completed:hover {
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.info {
|
||||
margin: 65px auto 0;
|
||||
color: #a6a6a6;
|
||||
font-size: 12px;
|
||||
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.info a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
/*
|
||||
Hack to remove background from Mobile Safari.
|
||||
Can't use it globally since it destroys checkboxes in Firefox and Opera
|
||||
*/
|
||||
@media screen and (-webkit-min-device-pixel-ratio:0) {
|
||||
.toggle-all,
|
||||
.todo-list li .toggle {
|
||||
background: none;
|
||||
}
|
||||
|
||||
.todo-list li .toggle {
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.toggle-all {
|
||||
top: -56px;
|
||||
left: -15px;
|
||||
width: 65px;
|
||||
height: 41px;
|
||||
-webkit-transform: rotate(90deg);
|
||||
transform: rotate(90deg);
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
}
|
||||
|
||||
.hidden{
|
||||
display:none;
|
||||
}
|
||||
|
||||
#benchmark {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.submitButton {
|
||||
display: none;
|
||||
}
|
||||
BIN
examples/todomvc/css/bg.png
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
19
examples/todomvc/index.html
Normal file
@@ -0,0 +1,19 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
||||
<title>React • TodoMVC</title>
|
||||
<link rel="stylesheet" href="css/base.css">
|
||||
<!--[if IE]>
|
||||
<script src="js/ie.js"></script>
|
||||
<![endif]-->
|
||||
</head>
|
||||
<body>
|
||||
<div id="todoapp"></div>
|
||||
<div id="benchmark"></div>
|
||||
<script src="../../build/react.js"></script>
|
||||
<script src="../../build/JSXTransformer.js"></script>
|
||||
<script type="text/jsx" src="js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
255
examples/todomvc/js/app.js
Normal file
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* @jsx React.DOM
|
||||
*/
|
||||
|
||||
var Utils = {
|
||||
// https://gist.github.com/1308368
|
||||
uuid: function(a,b){for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');return b},
|
||||
pluralize: function( count, word ) {
|
||||
return count === 1 ? word : word + 's';
|
||||
},
|
||||
store: function( namespace, data ) {
|
||||
if ( arguments.length > 1 ) {
|
||||
return localStorage.setItem( namespace, JSON.stringify( data ) );
|
||||
} else {
|
||||
var store = localStorage.getItem( namespace );
|
||||
return ( store && JSON.parse( store ) ) || [];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function cx(obj) {
|
||||
var s = '';
|
||||
for (var key in obj) {
|
||||
if (!obj.hasOwnProperty(key)) {
|
||||
continue;
|
||||
}
|
||||
if (obj[key]) {
|
||||
s += key + ' ';
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
var TodoItem = React.createClass({
|
||||
handleSubmit: function() {
|
||||
var val = this.state.editText;
|
||||
if (val) {
|
||||
this.props.onSave(val);
|
||||
this.setState({editField: ''});
|
||||
}
|
||||
return false;
|
||||
},
|
||||
handleEdit: function() {
|
||||
this.props.onEdit();
|
||||
this.refs.editField.getDOMNode().focus();
|
||||
},
|
||||
handleKey: function(event) {
|
||||
if (event.nativeEvent.keyCode === 27) {
|
||||
this.handleSubmit();
|
||||
}
|
||||
this.setState({editText: event.target.value});
|
||||
},
|
||||
getInitialState: function() {
|
||||
return {editText: this.props.todo.title};
|
||||
},
|
||||
componentWillReceiveProps: function(nextProps) {
|
||||
if (nextProps.todo.title !== this.props.todo.title) {
|
||||
this.setState(this.getInitialState());
|
||||
}
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<li class={cx({completed: this.props.todo.completed, editing: this.props.editing})}>
|
||||
<div class="view">
|
||||
<input
|
||||
class="toggle"
|
||||
type="checkbox"
|
||||
checked={this.props.todo.completed ? 'checked' : null}
|
||||
onChange={this.props.onToggle}
|
||||
/>
|
||||
<label onDoubleClick={this.handleEdit}>{this.props.todo.title}</label>
|
||||
<button class="destroy" onClick={this.props.onDestroy} />
|
||||
</div>
|
||||
<form onSubmit={this.handleSubmit}>
|
||||
<input
|
||||
ref="editField"
|
||||
class="edit"
|
||||
value={this.state.editText}
|
||||
onBlur={this.handleSubmit}
|
||||
onKeyUp={this.handleKey}
|
||||
/>
|
||||
<input type="submit" class="submitButton" />
|
||||
</form>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
var TodoFooter = React.createClass({
|
||||
render: function() {
|
||||
var activeTodoWord = Utils.pluralize(this.props.count, 'todo');
|
||||
var clearButton = null;
|
||||
|
||||
if (this.props.completedCount > 0) {
|
||||
clearButton = (
|
||||
<button class="clear-completed" onClick={this.props.onClearCompleted}>Clear completed ({this.props.completedCount})</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<footer class="footer">
|
||||
<span class="todo-count"><strong>{this.props.count}</strong>{' '}{activeTodoWord}{' '}left</span>
|
||||
{clearButton}
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
var TodoApp = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {
|
||||
todos: Utils.store('react-todos'),
|
||||
editing: {}
|
||||
};
|
||||
},
|
||||
|
||||
handleSubmit: function() {
|
||||
var val = this.refs.newField.getDOMNode().value.trim();
|
||||
if (val) {
|
||||
var todos = this.state.todos;
|
||||
var newTodo = {
|
||||
id: Utils.uuid(),
|
||||
title: val,
|
||||
completed: false
|
||||
};
|
||||
this.setState({todos: todos.concat([newTodo])});
|
||||
this.refs.newField.getDOMNode().value = '';
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
toggleAll: function(event) {
|
||||
var checked = event.nativeEvent.target.checked;
|
||||
this.state.todos.map(function(todo) {
|
||||
todo.completed = checked;
|
||||
});
|
||||
this.setState({todos: this.state.todos});
|
||||
},
|
||||
|
||||
toggle: function(todo) {
|
||||
todo.completed = !todo.completed;
|
||||
this.setState({todos: this.state.todos});
|
||||
},
|
||||
|
||||
destroy: function(todo) {
|
||||
var newTodos = this.state.todos.filter(function(candidate) {
|
||||
return candidate.id !== todo.id;
|
||||
});
|
||||
this.setState({todos: newTodos});
|
||||
},
|
||||
|
||||
edit: function(todo) {
|
||||
this.state.todos.map(function(todo) {
|
||||
this.state.editing[todo.id] = false;
|
||||
}.bind(this));
|
||||
this.state.editing[todo.id] = true;
|
||||
this.setState({editing: this.state.editing});
|
||||
},
|
||||
|
||||
save: function(todo, text) {
|
||||
todo.title = text;
|
||||
this.state.editing[todo.id] = false;
|
||||
this.setState({todos: this.state.todos, editing: this.state.editing});
|
||||
},
|
||||
|
||||
clearCompleted: function() {
|
||||
var newTodos = this.state.todos.filter(function(todo) {
|
||||
return !todo.completed;
|
||||
});
|
||||
this.setState({todos: newTodos});
|
||||
},
|
||||
|
||||
render: function() {
|
||||
Utils.store('react-todos', this.state.todos);
|
||||
var footer = null;
|
||||
var main = null;
|
||||
var todoItems = this.state.todos.map(function(todo) {
|
||||
return (
|
||||
<TodoItem
|
||||
todo={todo}
|
||||
onToggle={this.toggle.bind(this, todo)}
|
||||
onDestroy={this.destroy.bind(this, todo)}
|
||||
onEdit={this.edit.bind(this, todo)}
|
||||
editing={this.state.editing[todo.id]}
|
||||
onSave={this.save.bind(this, todo)}
|
||||
/>
|
||||
);
|
||||
}.bind(this));
|
||||
|
||||
var activeTodoCount = this.state.todos.filter(function(todo) {
|
||||
return !todo.completed;
|
||||
}).length;
|
||||
var completedCount = todoItems.length - activeTodoCount;
|
||||
if (activeTodoCount || completedCount) {
|
||||
footer =
|
||||
<TodoFooter
|
||||
count={activeTodoCount}
|
||||
completedCount={completedCount}
|
||||
onClearCompleted={this.clearCompleted.bind(this)}
|
||||
/>;
|
||||
}
|
||||
|
||||
if (todoItems.length) {
|
||||
main = (
|
||||
<section class="main">
|
||||
<input class="toggle-all" type="checkbox" onChange={this.toggleAll.bind(this)} />
|
||||
<label class="toggle-all-label">Mark all as complete</label>
|
||||
<ul class="todo-list">
|
||||
{todoItems}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<section class="todoapp">
|
||||
<header class="header">
|
||||
<h1>todos</h1>
|
||||
<form onSubmit={this.handleSubmit}>
|
||||
<input
|
||||
ref="newField"
|
||||
class="new-todo"
|
||||
placeholder="What needs to be done?"
|
||||
autofocus="autofocus"
|
||||
/>
|
||||
<input type="submit" class="submitButton" />
|
||||
</form>
|
||||
</header>
|
||||
{main}
|
||||
{footer}
|
||||
</section>
|
||||
<footer class="info">
|
||||
<p>Double-click to edit a todo</p>
|
||||
<p>Created by{' '}<a href="http://github.com/petehunt/">petehunt</a></p>
|
||||
<p>Part of{' '}<a href="http://todomvc.com">TodoMVC</a></p>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<TodoApp />, document.getElementById('todoapp'));
|
||||
|
||||
// Some benchmarking that requires either a custom build of React or more
|
||||
// modules exposed from React.*
|
||||
// var initTime = ReactMount.totalInstantiationTime + ReactMount.totalInjectionTime;
|
||||
// var benchmark = document.getElementById('benchmark');
|
||||
// setInterval(function() {
|
||||
// benchmark.innerHTML = (
|
||||
// 'Init render time = ' + initTime + 'ms' +
|
||||
// '<br />' +
|
||||
// 'Post-init render time = ' + (ReactMount.totalInstantiationTime + ReactMount.totalInjectionTime - initTime) + 'ms'
|
||||
// );
|
||||
// }, 1000);
|
||||
34
examples/todomvc/js/ie.js
Normal file
@@ -0,0 +1,34 @@
|
||||
/*! HTML5 Shiv pre3.6 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
|
||||
Uncompressed source: https://github.com/aFarkas/html5shiv */
|
||||
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
|
||||
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}</style>";
|
||||
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
|
||||
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment();
|
||||
for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
|
||||
|
||||
/* ES5-shim
|
||||
https://github.com/kriskowal/es5-shim
|
||||
Copyright 2009-2012 by contributors, MIT License */
|
||||
(function(definition){if(typeof define=="function")define(definition);else if(typeof YUI=="function")YUI.add("es5",definition);else definition()})(function(){if(!Function.prototype.bind)Function.prototype.bind=function bind(that){var target=this;if(typeof target!="function")throw new TypeError("Function.prototype.bind called on incompatible "+target);var args=slice.call(arguments,1);var bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));if(Object(result)===
|
||||
result)return result;return this}else return target.apply(that,args.concat(slice.call(arguments)))};if(target.prototype)bound.prototype=Object.create(target.prototype);return bound};var call=Function.prototype.call;var prototypeOfArray=Array.prototype;var prototypeOfObject=Object.prototype;var slice=prototypeOfArray.slice;var _toString=call.bind(prototypeOfObject.toString);var owns=call.bind(prototypeOfObject.hasOwnProperty);var defineGetter;var defineSetter;var lookupGetter;var lookupSetter;var supportsAccessors;
|
||||
if(supportsAccessors=owns(prototypeOfObject,"__defineGetter__")){defineGetter=call.bind(prototypeOfObject.__defineGetter__);defineSetter=call.bind(prototypeOfObject.__defineSetter__);lookupGetter=call.bind(prototypeOfObject.__lookupGetter__);lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)}if([1,2].splice(0).length!=2){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){if(!arguments.length)return[];else return array_splice.apply(this,[start===void 0?
|
||||
0:start,deleteCount===void 0?this.length-start:deleteCount].concat(slice.call(arguments,2)))}}if(!Array.isArray)Array.isArray=function isArray(obj){return _toString(obj)=="[object Array]"};var boxedString=Object("a"),splitString=boxedString[0]!="a"||!(0 in boxedString);if(!Array.prototype.forEach)Array.prototype.forEach=function forEach(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(_toString(fun)!=
|
||||
"[object Function]")throw new TypeError;while(++i<length)if(i in self)fun.call(thisp,self[i],i,object)};if(!Array.prototype.map)Array.prototype.map=function map(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");for(var i=0;i<length;i++)if(i in self)result[i]=fun.call(thisp,self[i],i,object);return result};
|
||||
if(!Array.prototype.filter)Array.prototype.filter=function filter(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>0,result=[],value,thisp=arguments[1];if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");for(var i=0;i<length;i++)if(i in self){value=self[i];if(fun.call(thisp,value,i,object))result.push(value)}return result};if(!Array.prototype.every)Array.prototype.every=function every(fun){var object=
|
||||
toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>0,thisp=arguments[1];if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");for(var i=0;i<length;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return false;return true};if(!Array.prototype.some)Array.prototype.some=function some(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>
|
||||
0,thisp=arguments[1];if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");for(var i=0;i<length;i++)if(i in self&&fun.call(thisp,self[i],i,object))return true;return false};if(!Array.prototype.reduce)Array.prototype.reduce=function reduce(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>0;if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");if(!length&&arguments.length==
|
||||
1)throw new TypeError("reduce of empty array with no initial value");var i=0;var result;if(arguments.length>=2)result=arguments[1];else{do{if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError("reduce of empty array with no initial value");}while(true)}for(;i<length;i++)if(i in self)result=fun.call(void 0,result,self[i],i,object);return result};if(!Array.prototype.reduceRight)Array.prototype.reduceRight=function reduceRight(fun){var object=toObject(this),self=splitString&&_toString(this)==
|
||||
"[object String]"?this.split(""):object,length=self.length>>>0;if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");if(!length&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else{do{if(i in self){result=self[i--];break}if(--i<0)throw new TypeError("reduceRight of empty array with no initial value");}while(true)}do if(i in this)result=fun.call(void 0,result,
|
||||
self[i],i,object);while(i--);return result};if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1)Array.prototype.indexOf=function indexOf(sought){var self=splitString&&_toString(this)=="[object String]"?this.split(""):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;if(arguments.length>1)i=toInteger(arguments[1]);i=i>=0?i:Math.max(0,length+i);for(;i<length;i++)if(i in self&&self[i]===sought)return i;return-1};if(!Array.prototype.lastIndexOf||[0,1].lastIndexOf(0,-3)!=-1)Array.prototype.lastIndexOf=
|
||||
function lastIndexOf(sought){var self=splitString&&_toString(this)=="[object String]"?this.split(""):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;if(arguments.length>1)i=Math.min(i,toInteger(arguments[1]));i=i>=0?i:length-Math.abs(i);for(;i>=0;i--)if(i in self&&sought===self[i])return i;return-1};if(!Object.keys){var hasDontEnumBug=true,dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=
|
||||
dontEnums.length;for(var key in{"toString":null})hasDontEnumBug=false;Object.keys=function keys(object){if(typeof object!="object"&&typeof object!="function"||object===null)throw new TypeError("Object.keys called on a non-object");var keys=[];for(var name in object)if(owns(object,name))keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;i<ii;i++){var dontEnum=dontEnums[i];if(owns(object,dontEnum))keys.push(dontEnum)}return keys}}var negativeDate=-621987552E5,negativeYearString="-000001";
|
||||
if(!Date.prototype.toISOString||(new Date(negativeDate)).toISOString().indexOf(negativeYearString)===-1)Date.prototype.toISOString=function toISOString(){var result,length,value,year,month;if(!isFinite(this))throw new RangeError("Date.prototype.toISOString called on non-finite value.");year=this.getUTCFullYear();month=this.getUTCMonth();year+=Math.floor(month/12);month=(month%12+12)%12;result=[month+1,this.getUTCDate(),this.getUTCHours(),this.getUTCMinutes(),this.getUTCSeconds()];year=(year<0?"-":
|
||||
year>9999?"+":"")+("00000"+Math.abs(year)).slice(0<=year&&year<=9999?-4:-6);length=result.length;while(length--){value=result[length];if(value<10)result[length]="0"+value}return year+"-"+result.slice(0,2).join("-")+"T"+result.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};var dateToJSONIsSupported=false;try{dateToJSONIsSupported=Date.prototype.toJSON&&(new Date(NaN)).toJSON()===null&&(new Date(negativeDate)).toJSON().indexOf(negativeYearString)!==-1&&Date.prototype.toJSON.call({toISOString:function(){return true}})}catch(e){}if(!dateToJSONIsSupported)Date.prototype.toJSON=
|
||||
function toJSON(key){var o=Object(this),tv=toPrimitive(o),toISO;if(typeof tv==="number"&&!isFinite(tv))return null;toISO=o.toISOString;if(typeof toISO!="function")throw new TypeError("toISOString property is not callable");return toISO.call(o)};if(!Date.parse||"Date.parse is buggy")Date=function(NativeDate){function Date(Y,M,D,h,m,s,ms){var length=arguments.length;if(this instanceof NativeDate){var date=length==1&&String(Y)===Y?new NativeDate(Date.parse(Y)):length>=7?new NativeDate(Y,M,D,h,m,s,ms):
|
||||
length>=6?new NativeDate(Y,M,D,h,m,s):length>=5?new NativeDate(Y,M,D,h,m):length>=4?new NativeDate(Y,M,D,h):length>=3?new NativeDate(Y,M,D):length>=2?new NativeDate(Y,M):length>=1?new NativeDate(Y):new NativeDate;date.constructor=Date;return date}return NativeDate.apply(this,arguments)}var isoDateExpression=new RegExp("^"+"(\\d{4}|[+-]\\d{6})"+"(?:-(\\d{2})"+"(?:-(\\d{2})"+"(?:"+"T(\\d{2})"+":(\\d{2})"+"(?:"+":(\\d{2})"+"(?:\\.(\\d{3}))?"+")?"+"("+"Z|"+"(?:"+"([-+])"+"(\\d{2})"+":(\\d{2})"+")"+")?)?)?)?"+
|
||||
"$");var months=[0,31,59,90,120,151,181,212,243,273,304,334,365];function dayFromMonth(year,month){var t=month>1?1:0;return months[month]+Math.floor((year-1969+t)/4)-Math.floor((year-1901+t)/100)+Math.floor((year-1601+t)/400)+365*(year-1970)}for(var key in NativeDate)Date[key]=NativeDate[key];Date.now=NativeDate.now;Date.UTC=NativeDate.UTC;Date.prototype=NativeDate.prototype;Date.prototype.constructor=Date;Date.parse=function parse(string){var match=isoDateExpression.exec(string);if(match){var year=
|
||||
Number(match[1]),month=Number(match[2]||1)-1,day=Number(match[3]||1)-1,hour=Number(match[4]||0),minute=Number(match[5]||0),second=Number(match[6]||0),millisecond=Number(match[7]||0),offset=!match[4]||match[8]?0:Number(new NativeDate(1970,0)),signOffset=match[9]==="-"?1:-1,hourOffset=Number(match[10]||0),minuteOffset=Number(match[11]||0),result;if(hour<(minute>0||second>0||millisecond>0?24:25)&&minute<60&&second<60&&millisecond<1E3&&month>-1&&month<12&&hourOffset<24&&minuteOffset<60&&day>-1&&day<dayFromMonth(year,
|
||||
month+1)-dayFromMonth(year,month)){result=((dayFromMonth(year,month)+day)*24+hour+hourOffset*signOffset)*60;result=((result+minute+minuteOffset*signOffset)*60+second)*1E3+millisecond+offset;if(-864E13<=result&&result<=864E13)return result}return NaN}return NativeDate.parse.apply(this,arguments)};return Date}(Date);if(!Date.now)Date.now=function now(){return(new Date).getTime()};if("0".split(void 0,0).length){var string_split=String.prototype.split;String.prototype.split=function(separator,limit){if(separator===
|
||||
void 0&&limit===0)return[];return string_split.apply(this,arguments)}}if("".substr&&"0b".substr(-1)!=="b"){var string_substr=String.prototype.substr;String.prototype.substr=function(start,length){return string_substr.call(this,start<0?(start=this.length+start)<0?0:start:start,length)}}var ws="\t\n\x0B\f\r \u00a0\u1680\u180e\u2000\u2001\u2002\u2003"+"\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028"+"\u2029\ufeff";if(!String.prototype.trim||ws.trim()){ws="["+ws+"]";var trimBeginRegexp=
|
||||
new RegExp("^"+ws+ws+"*"),trimEndRegexp=new RegExp(ws+ws+"*$");String.prototype.trim=function trim(){if(this===undefined||this===null)throw new TypeError("can't convert "+this+" to object");return String(this).replace(trimBeginRegexp,"").replace(trimEndRegexp,"")}}function toInteger(n){n=+n;if(n!==n)n=0;else if(n!==0&&n!==1/0&&n!==-(1/0))n=(n>0||-1)*Math.floor(Math.abs(n));return n}function isPrimitive(input){var type=typeof input;return input===null||type==="undefined"||type==="boolean"||type===
|
||||
"number"||type==="string"}function toPrimitive(input){var val,valueOf,toString;if(isPrimitive(input))return input;valueOf=input.valueOf;if(typeof valueOf==="function"){val=valueOf.call(input);if(isPrimitive(val))return val}toString=input.toString;if(typeof toString==="function"){val=toString.call(input);if(isPrimitive(val))return val}throw new TypeError;}var toObject=function(o){if(o==null)throw new TypeError("can't convert "+o+" to object");return Object(o)}});
|
||||
@@ -1,91 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
|
||||
<title>Basic Example with JSX</title>
|
||||
<link rel="stylesheet" href="../shared/css/base.css" />
|
||||
<link rel="stylesheet" href="transition.css" />
|
||||
</head>
|
||||
<body>
|
||||
<h1>Example with Transitions</h1>
|
||||
<div id="container">
|
||||
<p>
|
||||
To install React, follow the instructions on
|
||||
<a href="http://www.github.com/facebook/react/">GitHub</a>.
|
||||
</p>
|
||||
<p>
|
||||
If you can see this, React is not working right.
|
||||
If you checked out the source from GitHub make sure to run <code>grunt</code>.
|
||||
</p>
|
||||
</div>
|
||||
<h4>Example Details</h4>
|
||||
<ul>
|
||||
<li>
|
||||
This is built with
|
||||
<a href="https://github.com/substack/node-browserify">browserify</a>.
|
||||
</li>
|
||||
<li>
|
||||
This is written with JSX and transformed in the browser.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
</p>
|
||||
<p>
|
||||
Learn more at
|
||||
<a href="http://facebook.github.io/react" target="_blank">facebook.github.io/react</a>.
|
||||
</p>
|
||||
<script src="../../build/react-with-addons.js"></script>
|
||||
<script src="../../build/JSXTransformer.js"></script>
|
||||
<script type="text/jsx">
|
||||
/**
|
||||
* @jsx React.DOM
|
||||
*/
|
||||
var TransitionGroup = React.addons.TransitionGroup;
|
||||
var INTERVAL = 2000;
|
||||
|
||||
var AnimateDemo = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {start: 0};
|
||||
},
|
||||
|
||||
componentDidMount: function() {
|
||||
this.interval = setInterval(this.tick, INTERVAL);
|
||||
},
|
||||
|
||||
componentWillUnmount: function() {
|
||||
clearInterval(this.interval);
|
||||
},
|
||||
|
||||
tick: function() {
|
||||
this.setState({start: this.state.start + 1});
|
||||
},
|
||||
|
||||
render: function() {
|
||||
var children = [];
|
||||
var pos = 0;
|
||||
var colors = ['red', 'gray', 'blue'];
|
||||
for (var i = this.state.start; i < this.state.start + 3; i++) {
|
||||
var style = {
|
||||
left: pos * 128,
|
||||
background: colors[i % 3]
|
||||
};
|
||||
pos++;
|
||||
children.push(<div key={i} className="animateItem" style={style}>{i}</div>);
|
||||
}
|
||||
return (
|
||||
<TransitionGroup
|
||||
className="animateExample"
|
||||
transitionName="example">
|
||||
{children}
|
||||
</TransitionGroup>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(
|
||||
<AnimateDemo />,
|
||||
document.getElementById('container')
|
||||
);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,44 +0,0 @@
|
||||
.example-enter,
|
||||
.example-leave {
|
||||
-webkit-transition: all .25s;
|
||||
transition: all .25s;
|
||||
}
|
||||
|
||||
.example-enter,
|
||||
.example-leave.example-leave-active {
|
||||
opacity: 0.01;
|
||||
}
|
||||
|
||||
.example-leave.example-leave-active {
|
||||
margin-left: -128px;
|
||||
}
|
||||
|
||||
.example-enter {
|
||||
margin-left: 128px;
|
||||
}
|
||||
|
||||
.example-enter.example-enter-active,
|
||||
.example-leave {
|
||||
margin-left: 0;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.animateExample {
|
||||
display: block;
|
||||
height: 128px;
|
||||
position: relative;
|
||||
width: 384px;
|
||||
}
|
||||
|
||||
.animateItem {
|
||||
color: white;
|
||||
font-size: 36px;
|
||||
font-weight: bold;
|
||||
height: 128px;
|
||||
line-height: 128px;
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
-webkit-transition: all .25s; /* TODO: make this a move animation */
|
||||
transition: all .25s; /* TODO: make this a move animation */
|
||||
width: 128px;
|
||||
}
|
||||
@@ -37,16 +37,14 @@ function minify(src) {
|
||||
// TODO: move this out to another build step maybe.
|
||||
function bannerify(src) {
|
||||
var version = grunt.config.data.pkg.version;
|
||||
var packageName = this.data.packageName || this.data.standalone;
|
||||
return LICENSE_TEMPLATE.replace('@PACKAGE@', packageName)
|
||||
return LICENSE_TEMPLATE.replace('@PACKAGE@', this.data.standalone)
|
||||
.replace('@VERSION@', version) +
|
||||
'\n' + src;
|
||||
}
|
||||
|
||||
function simpleBannerify(src) {
|
||||
var version = grunt.config.data.pkg.version;
|
||||
var packageName = this.data.packageName || this.data.standalone;
|
||||
return SIMPLE_TEMPLATE.replace('@PACKAGE@', packageName)
|
||||
return SIMPLE_TEMPLATE.replace('@PACKAGE@', this.data.standalone)
|
||||
.replace('@VERSION@', version) +
|
||||
'\n' + src;
|
||||
}
|
||||
@@ -78,27 +76,8 @@ var transformer = {
|
||||
after: [simpleBannerify]
|
||||
};
|
||||
|
||||
var addons = {
|
||||
entries: [
|
||||
'./build/modules/ReactWithAddons.js'
|
||||
],
|
||||
outfile: './build/react-with-addons.js',
|
||||
debug: false,
|
||||
standalone: 'React',
|
||||
packageName: 'React (with addons)',
|
||||
after: [simpleBannerify]
|
||||
};
|
||||
|
||||
var addonsMin = grunt.util._.merge({}, addons, {
|
||||
outfile: './build/react-with-addons.min.js',
|
||||
debug: false,
|
||||
after: [minify, bannerify]
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
basic: basic,
|
||||
min: min,
|
||||
transformer: transformer,
|
||||
addons: addons,
|
||||
addonsMin: addonsMin
|
||||
transformer: transformer
|
||||
};
|
||||
|
||||
6
grunt/config/jsx/debug.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"debug": true,
|
||||
"constants": {
|
||||
"__DEV__": true
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,12 @@
|
||||
'use strict';
|
||||
|
||||
var grunt = require('grunt');
|
||||
|
||||
var rootIDs = [
|
||||
"React",
|
||||
"ReactWithAddons"
|
||||
"React"
|
||||
];
|
||||
|
||||
var getDebugConfig = function() {
|
||||
return {
|
||||
"debug": true,
|
||||
"constants": {
|
||||
"__VERSION__": grunt.config.data.pkg.version,
|
||||
"__DEV__": true
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
var debug = {
|
||||
rootIDs: rootIDs,
|
||||
getConfig: getDebugConfig,
|
||||
configFile: "grunt/config/jsx/debug.json",
|
||||
sourceDir: "src",
|
||||
outputDir: "build/modules"
|
||||
};
|
||||
@@ -28,7 +15,7 @@ var jasmine = {
|
||||
rootIDs: [
|
||||
"all"
|
||||
],
|
||||
getConfig: getDebugConfig,
|
||||
configFile: debug.configFile,
|
||||
sourceDir: "vendor/jasmine",
|
||||
outputDir: "build/jasmine"
|
||||
};
|
||||
@@ -38,37 +25,18 @@ var test = {
|
||||
"test/all.js",
|
||||
"**/__tests__/*.js"
|
||||
]),
|
||||
getConfig: function() {
|
||||
return {
|
||||
"debug": true,
|
||||
"mocking": true,
|
||||
"constants": {
|
||||
"__VERSION__": grunt.config.data.pkg.version,
|
||||
"__DEV__": true
|
||||
}
|
||||
};
|
||||
},
|
||||
configFile: "grunt/config/jsx/test.json",
|
||||
sourceDir: "src",
|
||||
outputDir: "build/modules"
|
||||
};
|
||||
|
||||
|
||||
var release = {
|
||||
rootIDs: rootIDs,
|
||||
getConfig: function() {
|
||||
return {
|
||||
"debug": false,
|
||||
"constants": {
|
||||
"__VERSION__": grunt.config.data.pkg.version,
|
||||
"__DEV__": false
|
||||
}
|
||||
};
|
||||
},
|
||||
configFile: "grunt/config/jsx/release.json",
|
||||
sourceDir: "src",
|
||||
outputDir: "build/modules"
|
||||
};
|
||||
|
||||
|
||||
module.exports = {
|
||||
debug: debug,
|
||||
jasmine: jasmine,
|
||||
|
||||
6
grunt/config/jsx/release.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"debug": false,
|
||||
"constants": {
|
||||
"__DEV__": false
|
||||
}
|
||||
}
|
||||
7
grunt/config/jsx/test.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"debug": true,
|
||||
"mocking": true,
|
||||
"constants": {
|
||||
"__DEV__": true
|
||||
}
|
||||
}
|
||||
1
grunt/config/version.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = '0.6.0';
|
||||
@@ -24,10 +24,10 @@ module.exports = function() {
|
||||
});
|
||||
|
||||
args.push.apply(args, rootIDs);
|
||||
args.push("--config" /* from stdin */);
|
||||
args.push("--config", config.configFile);
|
||||
|
||||
var child = spawn({
|
||||
cmd: "bin/jsx-internal",
|
||||
cmd: "bin/jsx",
|
||||
args: args
|
||||
}, function(error, result, code) {
|
||||
if (error) {
|
||||
@@ -38,9 +38,6 @@ module.exports = function() {
|
||||
}
|
||||
});
|
||||
|
||||
child.stdin.write(JSON.stringify(config.getConfig()));
|
||||
child.stdin.end();
|
||||
|
||||
child.stdout.pipe(process.stdout);
|
||||
child.stderr.pipe(process.stderr);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
var assert = require("assert");
|
||||
var fs = require("fs");
|
||||
var grunt = require("grunt");
|
||||
var spawn = grunt.util.spawn;
|
||||
var semver = require("semver");
|
||||
@@ -58,11 +59,13 @@ module.exports = function() {
|
||||
var config = this.data;
|
||||
var done = this.async();
|
||||
|
||||
spawn({
|
||||
cmd: phantomjs,
|
||||
args: ["--version"]
|
||||
}, function(error, result, code) {
|
||||
checkVersion(error, result, code);
|
||||
run(config, done);
|
||||
fs.chmod(phantomjs, 755, function(err) {
|
||||
spawn({
|
||||
cmd: phantomjs,
|
||||
args: ["--version"]
|
||||
}, function(error, result, code) {
|
||||
checkVersion(error, result, code);
|
||||
run(config, done);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
@@ -7,10 +7,7 @@ var grunt = require('grunt');
|
||||
|
||||
var BOWER_PATH = '../react-bower/';
|
||||
var BOWER_GLOB = [BOWER_PATH + '*'];
|
||||
var BOWER_FILES = [
|
||||
'react.js', 'react.min.js', 'JSXTransformer.js',
|
||||
'react-with-addons.js', 'react-with-addons.min.js'
|
||||
];
|
||||
var BOWER_FILES = ['react.js', 'react.min.js', 'JSXTransformer.js'];
|
||||
var GH_PAGES_PATH = '../react-gh-pages/';
|
||||
var GH_PAGES_GLOB = [GH_PAGES_PATH + '*'];
|
||||
|
||||
|
||||
2
main.js
@@ -2,7 +2,7 @@
|
||||
|
||||
var React = require('./build/modules/React');
|
||||
var visitors = require('./vendor/fbtransform/visitors').transformVisitors;
|
||||
var transform = require('jstransform').transform;
|
||||
var transform = require('./vendor/fbtransform/lib/transform').transform;
|
||||
|
||||
module.exports = {
|
||||
React: React,
|
||||
|
||||
1317
npm-shrinkwrap.json
generated
21
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-tools",
|
||||
"version": "0.5.2",
|
||||
"version": "0.4.2",
|
||||
"keywords": [
|
||||
"react",
|
||||
"jsx",
|
||||
@@ -36,24 +36,25 @@
|
||||
"test": "grunt build && grunt test"
|
||||
},
|
||||
"dependencies": {
|
||||
"base62": "~0.1.1",
|
||||
"commoner": "~0.8.4",
|
||||
"esprima-fb": "~1001.1001.2000-dev-harmony-fb",
|
||||
"jstransform": "~1.0.1"
|
||||
"esprima": "https://github.com/facebook/esprima/tarball/a3e0ea3979eb8d54d8bfade220c272903f928b1e",
|
||||
"recast": "~0.4.8",
|
||||
"source-map": "~0.1.22"
|
||||
},
|
||||
"devDependencies": {
|
||||
"browserify": "~2.34.1",
|
||||
"browserify": "~2.24.1",
|
||||
"wrapup": "~0.12.0",
|
||||
"populist": "~0.1.3",
|
||||
"grunt-cli": "~0.1.9",
|
||||
"grunt": "~0.4.1",
|
||||
"grunt-contrib-copy": "~0.4.1",
|
||||
"grunt-contrib-jshint": "~0.6.0",
|
||||
"optimist": "~0.6.0",
|
||||
"phantomjs": "~1.9.1-4",
|
||||
"recast": "~0.4.16",
|
||||
"semver": "~2.1.0",
|
||||
"uglify-js": "~2.4.0",
|
||||
"grunt-contrib-clean": "~0.5.0",
|
||||
"optimist": "~0.4.0",
|
||||
"phantomjs": ">= 1.9.0",
|
||||
"semver": "~2.0.0",
|
||||
"uglify-js": "~2.3.6",
|
||||
"grunt-contrib-clean": "~0.4.1",
|
||||
"grunt-compare-size": "~0.4.0",
|
||||
"gzip-js": "~0.3.2",
|
||||
"tmp": "~0.0.18",
|
||||
|
||||
@@ -17,8 +17,6 @@ gemspec = Gem::Specification.new do |s|
|
||||
s.files = Dir[
|
||||
'build/react.js',
|
||||
'build/react.min.js',
|
||||
'build/react-with-addons.js',
|
||||
'build/react-with-addons.min.js',
|
||||
'build/JSXTransformer.js',
|
||||
'lib/react/source.rb'
|
||||
]
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
# Generate an AUTHORS file based on the output of git shortlog. It uses ABC
|
||||
# order, strips out leading spaces and numbers, then filters out specific
|
||||
# authors.
|
||||
|
||||
git shortlog -se \
|
||||
| perl -spe 's/^\s+\d+\s+//' \
|
||||
| sed -e '/^CommitSyncScript.*$/d' \
|
||||
> AUTHORS
|
||||