Compare commits
59 Commits
pr32829
...
0.5-stable
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b809ffbc4 | ||
|
|
e6912a7a4a | ||
|
|
f1ae3392bd | ||
|
|
94a9a3e752 | ||
|
|
48af9c7bda | ||
|
|
1da10d718d | ||
|
|
ef8bd04b04 | ||
|
|
030835b914 | ||
|
|
abf199d5ff | ||
|
|
1053a1453a | ||
|
|
b8194d92f6 | ||
|
|
18a6b0b94b | ||
|
|
0b31175238 | ||
|
|
6a0bb61b16 | ||
|
|
c065b03b8a | ||
|
|
c32c788e5a | ||
|
|
4a0a14d319 | ||
|
|
a55d44efaf | ||
|
|
08fcec503c | ||
|
|
cd6d43e4c0 | ||
|
|
c329eb6335 | ||
|
|
215988f879 | ||
|
|
fb7e157cba | ||
|
|
8ead6dce76 | ||
|
|
79b09d9597 | ||
|
|
fb1a072739 | ||
|
|
c1c7a601dd | ||
|
|
adad0d72be | ||
|
|
e7f48a6c00 | ||
|
|
d3cee1ee2e | ||
|
|
d47d509637 | ||
|
|
411419c361 | ||
|
|
fc67d5544c | ||
|
|
4faad1a32a | ||
|
|
01b40d84c7 | ||
|
|
67d0f15d1a | ||
|
|
e5f03ae407 | ||
|
|
25140e5a0d | ||
|
|
b5804fa565 | ||
|
|
1bb2651660 | ||
|
|
b21cdac9e3 | ||
|
|
92ce80cf4f | ||
|
|
f3db0006e8 | ||
|
|
ef4d7a37f0 | ||
|
|
64016811d3 | ||
|
|
7b957c880c | ||
|
|
1b835fb5cf | ||
|
|
9f0bbce797 | ||
|
|
c9d20e56d3 | ||
|
|
ce612904ef | ||
|
|
ea1ab5501d | ||
|
|
2c35ed8068 | ||
|
|
c994cc24c3 | ||
|
|
24da1c0023 | ||
|
|
d82181e4b9 | ||
|
|
ba166b9652 | ||
|
|
f756cb3d9c | ||
|
|
cadf8b786c | ||
|
|
953947a617 |
2
AUTHORS
@@ -5,6 +5,7 @@ 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>
|
||||
@@ -18,6 +19,7 @@ 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>
|
||||
|
||||
56
CHANGELOG.md
@@ -1,3 +1,59 @@
|
||||
## 0.5.2, 0.4.2 (December 18, 2013)
|
||||
|
||||
### React
|
||||
|
||||
* Fixed a potential XSS vulnerability when using user content as a `key`: [CVE-2013-7035](https://groups.google.com/forum/#!topic/reactjs/OIqxlB2aGfU)
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
24
README.md
@@ -2,21 +2,21 @@
|
||||
|
||||
React is a JavaScript library for building user interfaces.
|
||||
|
||||
* **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.
|
||||
* **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.
|
||||
|
||||
[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>;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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.4.1.js"></script>
|
||||
<script src="http://fb.me/react-0.5.2.js"></script>
|
||||
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
|
||||
<script src="http://fb.me/JSXTransformer-0.4.1.js"></script>
|
||||
<script src="http://fb.me/JSXTransformer-0.5.2.js"></script>
|
||||
```
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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,12 +81,10 @@ 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
|
||||
# Create test build & run tests with PhantomJS
|
||||
# Build and run tests with PhantomJS
|
||||
grunt test
|
||||
# Lint the core library code with JSHint
|
||||
# Lint the code with JSHint
|
||||
grunt lint
|
||||
# Lint package code
|
||||
grunt lint:package
|
||||
# Wipe out build directory
|
||||
grunt clean
|
||||
```
|
||||
|
||||
@@ -3,7 +3,7 @@ source 'https://rubygems.org'
|
||||
gem 'rake'
|
||||
|
||||
# jekyll, which builds it all
|
||||
gem 'jekyll', '~>1.0'
|
||||
gem 'jekyll', '~>1.3.0'
|
||||
|
||||
# JSON
|
||||
gem 'json'
|
||||
|
||||
@@ -4,40 +4,47 @@ GEM
|
||||
classifier (1.3.3)
|
||||
fast-stemmer (>= 1.0.0)
|
||||
colorator (0.1)
|
||||
commander (4.1.3)
|
||||
commander (4.1.5)
|
||||
highline (~> 1.6.11)
|
||||
directory_watcher (1.4.1)
|
||||
fast-stemmer (1.0.2)
|
||||
highline (1.6.19)
|
||||
jekyll (1.0.2)
|
||||
ffi (1.9.3)
|
||||
highline (1.6.20)
|
||||
jekyll (1.3.0)
|
||||
classifier (~> 1.3)
|
||||
colorator (~> 0.1)
|
||||
commander (~> 4.1.3)
|
||||
directory_watcher (~> 1.4.1)
|
||||
kramdown (~> 1.0.2)
|
||||
liquid (~> 2.3)
|
||||
maruku (~> 0.5)
|
||||
liquid (~> 2.5.2)
|
||||
listen (~> 1.3)
|
||||
maruku (~> 0.6.0)
|
||||
pygments.rb (~> 0.5.0)
|
||||
safe_yaml (~> 0.7.0)
|
||||
json (1.8.0)
|
||||
kramdown (1.0.2)
|
||||
liquid (2.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)
|
||||
maruku (0.6.1)
|
||||
syntax (>= 1.0.0)
|
||||
mini_portile (0.5.1)
|
||||
mini_portile (0.5.2)
|
||||
nokogiri (1.6.0)
|
||||
mini_portile (~> 0.5.0)
|
||||
posix-spawn (0.3.6)
|
||||
pygments.rb (0.5.0)
|
||||
pygments.rb (0.5.4)
|
||||
posix-spawn (~> 0.3.6)
|
||||
yajl-ruby (~> 1.1.0)
|
||||
rake (10.0.4)
|
||||
rake (10.1.0)
|
||||
rb-fsevent (0.9.3)
|
||||
redcarpet (2.2.2)
|
||||
safe_yaml (0.7.1)
|
||||
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)
|
||||
sanitize (2.0.6)
|
||||
nokogiri (>= 1.4.4)
|
||||
sass (3.2.9)
|
||||
sass (3.2.12)
|
||||
syntax (1.0.0)
|
||||
yajl-ruby (1.1.0)
|
||||
|
||||
@@ -45,7 +52,7 @@ PLATFORMS
|
||||
ruby
|
||||
|
||||
DEPENDENCIES
|
||||
jekyll (~> 1.0)
|
||||
jekyll (~> 1.3.0)
|
||||
json
|
||||
rake
|
||||
rb-fsevent
|
||||
|
||||
@@ -21,6 +21,7 @@ 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,59 +13,8 @@ redcarpet:
|
||||
pygments: true
|
||||
name: React
|
||||
markdown: redcarpet
|
||||
react_version: 0.4.0
|
||||
react_version: 0.5.2
|
||||
description: A JavaScript library for building user interfaces
|
||||
relative_permalinks: true
|
||||
paginate: 5
|
||||
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: addons
|
||||
title: Add-ons
|
||||
- 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
|
||||
paginate_path: /blog/page:num/
|
||||
|
||||
@@ -15,6 +15,7 @@ $contentPadding: 20px;
|
||||
$columnWidth: 280px;
|
||||
$columnGutter: 40px;
|
||||
$twoColumnWidth: 2 * $columnWidth + $columnGutter;
|
||||
$navHeight: 50px;
|
||||
|
||||
|
||||
|
||||
@@ -42,7 +43,7 @@ html {
|
||||
|
||||
|
||||
.container {
|
||||
padding-top: 50px;
|
||||
padding-top: $navHeight;
|
||||
min-width: $contentWidth + (2 * $contentPadding);
|
||||
}
|
||||
|
||||
@@ -73,6 +74,23 @@ 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 {
|
||||
@@ -81,7 +99,7 @@ li {
|
||||
color: $lightTextColor;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
height: 50px;
|
||||
height: $navHeight;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, .5);
|
||||
width: 100%;
|
||||
z-index: 100;
|
||||
@@ -103,9 +121,9 @@ li {
|
||||
padding: 0 8px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
line-height: 50px;
|
||||
line-height: $navHeight;
|
||||
display: inline-block;
|
||||
height: 50px;
|
||||
height: $navHeight;
|
||||
color: $mediumTextColor;
|
||||
|
||||
&:hover {
|
||||
@@ -123,7 +141,7 @@ li {
|
||||
.nav-home {
|
||||
color: #00d8ff;
|
||||
font-size: 24px;
|
||||
line-height: 50px;
|
||||
line-height: $navHeight;
|
||||
}
|
||||
|
||||
.nav-logo {
|
||||
@@ -369,6 +387,8 @@ section.black content {
|
||||
*/
|
||||
|
||||
.blogContent {
|
||||
@include clearfix;
|
||||
|
||||
padding-top: 20px;
|
||||
|
||||
blockquote {
|
||||
@@ -391,6 +411,7 @@ section.black content {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
|
||||
// H2s form documentation topic dividers. Extra space helps.
|
||||
h2 {
|
||||
margin-top: 30px;
|
||||
@@ -438,7 +459,7 @@ section.black content {
|
||||
}
|
||||
|
||||
.playgroundPreview {
|
||||
padding: 14px;
|
||||
padding: 0;
|
||||
width: 600px;
|
||||
|
||||
pre {
|
||||
|
||||
57
docs/_data/nav_docs.yml
Normal file
@@ -0,0 +1,57 @@
|
||||
- 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
|
||||
30
docs/_data/nav_tips.yml
Normal file
@@ -0,0 +1,30 @@
|
||||
- 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,5 +1,6 @@
|
||||
<div class="nav-docs">
|
||||
{% for section in site.nav_docs_sections %}
|
||||
<!-- Docs Nav -->
|
||||
{% for section in site.data.nav_docs %}
|
||||
<div class="nav-docs-section">
|
||||
<h3>{{ section.title }}</h3>
|
||||
<ul>
|
||||
@@ -24,4 +25,18 @@
|
||||
</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,7 +22,8 @@ var CodeMirrorEditor = React.createClass({
|
||||
mode: 'javascript',
|
||||
lineNumbers: false,
|
||||
matchBrackets: true,
|
||||
theme: 'solarized-light'
|
||||
theme: 'solarized-light',
|
||||
readOnly: this.props.readOnly
|
||||
});
|
||||
this.editor.on('change', this.onChange);
|
||||
this.onChange();
|
||||
@@ -44,7 +45,7 @@ var CodeMirrorEditor = React.createClass({
|
||||
}
|
||||
|
||||
return (
|
||||
<div class={this.props.className}>
|
||||
<div className={this.props.className}>
|
||||
{editor}
|
||||
</div>
|
||||
);
|
||||
@@ -76,22 +77,22 @@ var ReactPlayground = React.createClass({
|
||||
content =
|
||||
<CodeMirrorEditor
|
||||
onChange={this.bindState('code')}
|
||||
class="playgroundStage"
|
||||
className="playgroundStage"
|
||||
codeText={this.state.code}
|
||||
/>;
|
||||
} else if (this.state.mode === this.MODES.JS) {
|
||||
content =
|
||||
<div class="playgroundJS playgroundStage">
|
||||
{this.getDesugaredCode()}
|
||||
<div className="playgroundJS playgroundStage">
|
||||
{this.getDesugaredCode()}
|
||||
</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="playground">
|
||||
<div class="playgroundCode">
|
||||
<div className="playground">
|
||||
<div className="playgroundCode">
|
||||
{content}
|
||||
</div>
|
||||
<div class="playgroundPreview">
|
||||
<div className="playgroundPreview">
|
||||
<div ref="mount" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -111,17 +112,18 @@ var ReactPlayground = React.createClass({
|
||||
} catch (e) { }
|
||||
|
||||
try {
|
||||
var desugaredCode = this.getDesugaredCode();
|
||||
if (this.props.renderCode) {
|
||||
React.renderComponent(
|
||||
<pre>{this.getDesugaredCode()}</pre>,
|
||||
<CodeMirrorEditor codeText={desugaredCode} readOnly={true} />,
|
||||
mountNode
|
||||
);
|
||||
} else {
|
||||
eval(this.getDesugaredCode());
|
||||
eval(desugaredCode);
|
||||
}
|
||||
} catch (e) {
|
||||
React.renderComponent(
|
||||
<div content={e.toString()} class="playgroundError" />,
|
||||
<div content={e.toString()} className="playgroundError" />,
|
||||
mountNode
|
||||
);
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@
|
||||
</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),
|
||||
|
||||
25
docs/_layouts/tips.html
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
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} id=\"#{clean_title}\">#{title}</h#{level}>"
|
||||
return "<h#{level}><a class=\"anchor\" name=\"#{clean_title}\"></a>#{title} <a class=\"hash-link\" href=\"##{clean_title}\">#</a></h#{level}>"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
52
docs/_posts/2013-10-16-react-v0.5.0.md
Normal file
@@ -0,0 +1,52 @@
|
||||
---
|
||||
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.
|
||||
25
docs/_posts/2013-10-29-react-v0-5-1.md
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
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
|
||||
|
||||
143
docs/_posts/2013-11-05-thinking-in-react.md
Normal file
@@ -0,0 +1,143 @@
|
||||
---
|
||||
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 :)
|
||||
125
docs/_posts/2013-11-06-community-roundup-10.md
Normal file
@@ -0,0 +1,125 @@
|
||||
---
|
||||
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>
|
||||
92
docs/_posts/2013-11-18-community-roundup-11.md
Normal file
@@ -0,0 +1,92 @@
|
||||
---
|
||||
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>
|
||||
23
docs/_posts/2013-12-18-react-v0.5.2-v0.4.2.md
Normal file
@@ -0,0 +1,23 @@
|
||||
---
|
||||
title: "React v0.5.2, v0.4.2"
|
||||
layout: post
|
||||
author: Paul O'Shannessy
|
||||
---
|
||||
|
||||
Today we're releasing an update to address a potential XSS vulnerability that can arise when using user data as a `key`. Typically "safe" data is used for a `key`, for example, an id from your database, or a unique hash. However there are cases where it may be reasonable to use user generated content. A carefully crafted piece of content could result in arbitrary JS execution. While we make a very concerted effort to ensure all text is escaped before inserting it into the DOM, we missed one case. Immediately following the discovery of this vulnerability, we performed an audit to ensure we this was the only such vulnerability.
|
||||
|
||||
This only affects v0.5.x and v0.4.x. Versions in the 0.3.x family are unaffected.
|
||||
|
||||
Updated versions are available for immediate download via npm, bower, and on our [download page][download].
|
||||
|
||||
We take security very seriously at Facebook. For most of our products, users don't need to know that a security issue has been fixed. But with libraries like React, we need to make sure developers using React have access to fixes to keep their users safe.
|
||||
|
||||
While we've encouraged responsible disclosure as part of [Facebook's whitehat bounty program][bounty] since we launched, we don't have a good process for notifying our users. Hopefully we don't need to use it, but moving forward we'll set up a little bit more process to ensure the safety of our users. Ember.js has [an excellent policy][ember] which we may use as our model.
|
||||
|
||||
You can learn more about the vulnerability discussed here: [CVE-2013-7035][cve].
|
||||
|
||||
[download]: http://facebook.github.io/react/downloads.html
|
||||
[bounty]: https://www.facebook.com/whitehat/
|
||||
[ember]: http://emberjs.com/security/
|
||||
[cve]: https://groups.google.com/forum/#!topic/reactjs/OIqxlB2aGfU
|
||||
|
||||
@@ -20,12 +20,12 @@ sectionid: blog
|
||||
|
||||
<div class="pagination">
|
||||
{% if paginator.previous_page %}
|
||||
<a href="/react/blog/{{ paginator.previous_page_path }}" class="previous">
|
||||
<a href="/react/{{ paginator.previous_page_path }}" class="previous">
|
||||
« Previous Page
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if paginator.next_page %}
|
||||
<a href="/react/blog/{{ paginator.next_page_path }}" class="next">
|
||||
<a href="/react{{ paginator.next_page_path }}" class="next">
|
||||
Next Page »
|
||||
</a>
|
||||
{% endif %}
|
||||
|
||||
@@ -157,19 +157,6 @@ 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
|
||||
|
||||
|
||||
@@ -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: autoBind and Event Delegation
|
||||
## Under the Hood: Autobinding and Event Delegation
|
||||
|
||||
Under the hood React does a few things to keep your code performant and easy to understand.
|
||||
|
||||
|
||||
@@ -130,3 +130,18 @@ 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.
|
||||
|
||||
@@ -47,6 +47,14 @@ 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.
|
||||
|
||||
@@ -4,207 +4,13 @@ title: Add-ons
|
||||
layout: docs
|
||||
permalink: addons.html
|
||||
prev: tooling-integration.html
|
||||
next: examples.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.
|
||||
`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:
|
||||
|
||||
## CSS Animation and Transitions
|
||||
- `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.
|
||||
|
||||
`ReactTransitions` is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM. `ReactTransitions` is 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, 0)
|
||||
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 `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: 0.99;
|
||||
}
|
||||
```
|
||||
|
||||
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 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: 0.99;
|
||||
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>
|
||||
```
|
||||
|
||||
`component` does not need to be a DOM component. It can be any component you want; even one you've written yourself!
|
||||
|
||||
## ReactLink
|
||||
|
||||
`ReactLink` is an easy way to express two-way binding with React.
|
||||
|
||||
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!
|
||||
To get the add-ons, use `react-with-addons.js` (and its minified counterpart) rather than the common `react.js`.
|
||||
|
||||
99
docs/docs/09.1-animation.md
Normal file
@@ -0,0 +1,99 @@
|
||||
---
|
||||
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!
|
||||
117
docs/docs/09.2-form-input-binding-sugar.md
Normal file
@@ -0,0 +1,117 @@
|
||||
---
|
||||
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!
|
||||
46
docs/docs/09.3-class-name-manipulation.md
Normal file
@@ -0,0 +1,46 @@
|
||||
---
|
||||
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!
|
||||
@@ -1,96 +0,0 @@
|
||||
---
|
||||
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,14 +53,18 @@ 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.unmountAndReleaseReactRootNode
|
||||
### React.unmountComponentAtNode
|
||||
|
||||
```javascript
|
||||
unmountAndReleaseReactRootNode(DOMElement container)
|
||||
unmountComponentAtNode(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({
|
||||
}
|
||||
});
|
||||
|
||||
// <AvatarImage userId={17} width={200} height={200} />
|
||||
// <Avatar 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 when the component is mounted. The return value will be used as the initial value of `this.state`.
|
||||
Invoked once before the component is mounted. The return value will be used as the initial value of `this.state`.
|
||||
|
||||
|
||||
### getDefaultProps
|
||||
|
||||
@@ -36,8 +36,11 @@ 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 that 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:
|
||||
>
|
||||
> 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).
|
||||
|
||||
|
||||
@@ -128,25 +128,6 @@ 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 class="commentBox">
|
||||
<div className="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 class="commentList">
|
||||
<div className="commentList">
|
||||
Hello, world! I am a CommentList.
|
||||
</div>
|
||||
);
|
||||
@@ -130,7 +130,7 @@ var CommentList = React.createClass({
|
||||
var CommentForm = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div class="commentForm">
|
||||
<div className="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 class="commentBox">
|
||||
<div className="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 class="commentList">
|
||||
<div className="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 class="comment">
|
||||
<h2 class="commentAuthor">
|
||||
<div className="comment">
|
||||
<h2 className="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 class="comment">
|
||||
<h2 class="commentAuthor">
|
||||
<div className="comment">
|
||||
<h2 className="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 class="comment">
|
||||
<h2 class="commentAuthor">
|
||||
<div className="comment">
|
||||
<h2 className="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 class="commentBox">
|
||||
<div className="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 class="commentList">
|
||||
<div className="commentList">
|
||||
{commentNodes}
|
||||
</div>
|
||||
);
|
||||
@@ -346,7 +346,7 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div class="commentBox">
|
||||
<div className="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 1.5 to help make an asynchronous request to the server.
|
||||
We will use jQuery 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,8 +379,6 @@ var CommentBox = React.createClass({
|
||||
getInitialState: function() {
|
||||
$.ajax({
|
||||
url: 'comments.json',
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -389,7 +387,7 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div class="commentBox">
|
||||
<div className="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm />
|
||||
@@ -407,8 +405,6 @@ var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -419,14 +415,11 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
componentWillMount: function() {
|
||||
this.loadCommentsFromServer();
|
||||
setInterval(
|
||||
this.loadCommentsFromServer.bind(this),
|
||||
this.props.pollInterval
|
||||
);
|
||||
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div class="commentBox">
|
||||
<div className="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm />
|
||||
@@ -436,13 +429,13 @@ var CommentBox = React.createClass({
|
||||
});
|
||||
|
||||
React.renderComponent(
|
||||
<CommentBox url="comments.json" pollInterval={5000} />,
|
||||
<CommentBox url="comments.json" pollInterval={2000} />,
|
||||
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 5 seconds after that. Try running this in your browser and changing the `comments.json` file; within 5 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 2 seconds after that. Try running this in your browser and changing the `comments.json` file; within 2 seconds, the changes will show!
|
||||
|
||||
### Adding new comments
|
||||
|
||||
@@ -453,10 +446,10 @@ Now it's time to build the form. Our `CommentForm` component should ask the user
|
||||
var CommentForm = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<form class="commentForm">
|
||||
<form className="commentForm">
|
||||
<input type="text" placeholder="Your name" />
|
||||
<input type="text" placeholder="Say something..." />
|
||||
<input type="submit" />
|
||||
<input type="submit" value="Post" />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -481,14 +474,14 @@ var CommentForm = React.createClass({
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<form class="commentForm" onSubmit={this.handleSubmit}>
|
||||
<form className="commentForm" onSubmit={this.handleSubmit}>
|
||||
<input type="text" placeholder="Your name" ref="author" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Say something..."
|
||||
ref="text"
|
||||
/>
|
||||
<input type="submit" />
|
||||
<input type="submit" value="Post" />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -517,8 +510,6 @@ var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -532,14 +523,11 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
componentWillMount: function() {
|
||||
this.loadCommentsFromServer();
|
||||
setInterval(
|
||||
this.loadCommentsFromServer.bind(this),
|
||||
this.props.pollInterval
|
||||
);
|
||||
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div class="commentBox">
|
||||
<div className="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
@@ -566,14 +554,14 @@ var CommentForm = React.createClass({
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<form class="commentForm" onSubmit={this.handleSubmit}>
|
||||
<form className="commentForm" onSubmit={this.handleSubmit}>
|
||||
<input type="text" placeholder="Your name" ref="author" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Say something..."
|
||||
ref="text"
|
||||
/>
|
||||
<input type="submit" />
|
||||
<input type="submit" value="Post" />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -588,8 +576,6 @@ var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -598,9 +584,8 @@ 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)
|
||||
@@ -611,14 +596,11 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
componentWillMount: function() {
|
||||
this.loadCommentsFromServer();
|
||||
setInterval(
|
||||
this.loadCommentsFromServer.bind(this),
|
||||
this.props.pollInterval
|
||||
);
|
||||
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div class="commentBox">
|
||||
<div className="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
@@ -640,8 +622,6 @@ var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -649,13 +629,12 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
handleCommentSubmit: function(comment) {
|
||||
var comments = this.state.data;
|
||||
comments.push(comment);
|
||||
this.setState({data: comments});
|
||||
var newComments = comments.concat([comment]);
|
||||
this.setState({data: newComments});
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
type: 'POST',
|
||||
data: comment,
|
||||
dataType: 'json',
|
||||
mimeType: 'textPlain',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -666,14 +645,11 @@ var CommentBox = React.createClass({
|
||||
},
|
||||
componentWillMount: function() {
|
||||
this.loadCommentsFromServer();
|
||||
setInterval(
|
||||
this.loadCommentsFromServer.bind(this),
|
||||
this.props.pollInterval
|
||||
);
|
||||
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div class="commentBox">
|
||||
<div className="commentBox">
|
||||
<h1>Comments</h1>
|
||||
<CommentList data={this.state.data} />
|
||||
<CommentForm
|
||||
|
||||
@@ -28,6 +28,20 @@ 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.
|
||||
|
||||
|
||||
BIN
docs/img/blog/genesis_skeleton.png
Normal file
|
After Width: | Height: | Size: 168 KiB |
BIN
docs/img/blog/guess_filter.jpg
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
docs/img/blog/react-php.png
Normal file
|
After Width: | Height: | Size: 42 KiB |
BIN
docs/img/blog/steve_reverse.gif
Normal file
|
After Width: | Height: | Size: 5.4 MiB |
BIN
docs/img/blog/thinking-in-react-components.png
Normal file
|
After Width: | Height: | Size: 28 KiB |
BIN
docs/img/blog/thinking-in-react-mock.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
docs/img/blog/tutsplus.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
docs/img/blog/xoxo2013.png
Normal file
|
After Width: | Height: | Size: 246 KiB |
@@ -7,23 +7,25 @@ id: home
|
||||
<section class="light home-section">
|
||||
<div class="marketing-row">
|
||||
<div class="marketing-col">
|
||||
<h3>Declarative</h3>
|
||||
<h3>Just the UI</h3>
|
||||
<p>
|
||||
React uses a declarative paradigm that makes it easier to reason about
|
||||
your application.
|
||||
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.
|
||||
</p>
|
||||
</div>
|
||||
<div class="marketing-col">
|
||||
<h3>Efficient</h3>
|
||||
<h3>Virtual DOM</h3>
|
||||
<p>
|
||||
React computes the minimal set of changes necessary to keep your DOM
|
||||
up-to-date.
|
||||
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.
|
||||
</p>
|
||||
</div>
|
||||
<div class="marketing-col">
|
||||
<h3>Flexible</h3>
|
||||
<h3>Data flow</h3>
|
||||
<p>
|
||||
React works with the libraries and frameworks that you already know.
|
||||
React implements one-way reactive data flow which reduces boilerplate and is
|
||||
easier to reason about than traditional data binding.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -60,7 +62,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>
|
||||
|
||||
13
docs/tips/01-introduction.md
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
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.
|
||||
24
docs/tips/02-inline-styles.md
Normal file
@@ -0,0 +1,24 @@
|
||||
---
|
||||
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".
|
||||
42
docs/tips/03-if-else-in-JSX.md
Normal file
@@ -0,0 +1,42 @@
|
||||
---
|
||||
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).
|
||||
14
docs/tips/04-self-closing-tag.md
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
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.
|
||||
12
docs/tips/05-maximum-number-of-jsx-root-nodes.md
Normal file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
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.
|
||||
29
docs/tips/06-style-props-value-px.md
Normal file
@@ -0,0 +1,29 @@
|
||||
---
|
||||
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`
|
||||
49
docs/tips/07-children-props-type.md
Normal file
@@ -0,0 +1,49 @@
|
||||
---
|
||||
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);
|
||||
```
|
||||
24
docs/tips/08-controlled-input-null-value.md
Normal file
@@ -0,0 +1,24 @@
|
||||
---
|
||||
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);
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
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.
|
||||
62
docs/tips/10-props-in-getInitialState-as-anti-pattern.md
Normal file
@@ -0,0 +1,62 @@
|
||||
---
|
||||
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);
|
||||
```
|
||||
46
docs/tips/11-dom-event-listeners.md
Normal file
@@ -0,0 +1,46 @@
|
||||
---
|
||||
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).
|
||||
47
docs/tips/12-initial-ajax.md
Normal file
@@ -0,0 +1,47 @@
|
||||
---
|
||||
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
|
||||
);
|
||||
```
|
||||
33
docs/tips/13-false-in-jsx.md
Normal file
@@ -0,0 +1,33 @@
|
||||
---
|
||||
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>`.
|
||||
40
docs/tips/14-communicate-between-components.md
Normal file
@@ -0,0 +1,40 @@
|
||||
---
|
||||
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.
|
||||
@@ -20,7 +20,7 @@
|
||||
.example-enter.example-enter-active,
|
||||
.example-leave {
|
||||
margin-left: 0;
|
||||
opacity: 0.99;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.animateExample {
|
||||
|
||||
@@ -64,8 +64,8 @@ module.exports = function() {
|
||||
var pkgDir = path.join(nodePath, pkg.name);
|
||||
var doneCount = 2;
|
||||
|
||||
// Make sure that bin/jsx-internal is runnable by echoing main.js.
|
||||
run("bin/jsx-internal", ["main.js"], {
|
||||
// Make sure that bin/jsx is runnable by echoing main.js.
|
||||
run("bin/jsx", ["main.js"], {
|
||||
cwd: pkgDir
|
||||
}, function(result) {
|
||||
assert.ok(result.stdout.indexOf("transform") >= 0, result.stdout);
|
||||
|
||||
1317
npm-shrinkwrap.json
generated
Normal file
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-tools",
|
||||
"version": "0.5.0-alpha",
|
||||
"version": "0.5.2",
|
||||
"keywords": [
|
||||
"react",
|
||||
"jsx",
|
||||
|
||||
@@ -44,9 +44,10 @@ function detectEvents() {
|
||||
var testEl = document.createElement('div');
|
||||
var style = testEl.style;
|
||||
for (var baseEventName in EVENT_NAME_MAP) {
|
||||
for (var styleName in baseEventName) {
|
||||
var baseEvents = EVENT_NAME_MAP[baseEventName];
|
||||
for (var styleName in baseEvents) {
|
||||
if (styleName in style) {
|
||||
endEvents.push(EVENT_NAME_MAP[styleName]);
|
||||
endEvents.push(baseEvents[styleName]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,6 @@ var React = {
|
||||
|
||||
// Version exists only in the open-source version of React, not in Facebook's
|
||||
// internal version.
|
||||
React.version = '0.5.0-alpha';
|
||||
React.version = '0.5.2';
|
||||
|
||||
module.exports = React;
|
||||
|
||||
@@ -430,6 +430,10 @@ var ReactMount = {
|
||||
unmountComponentFromNode: function(instance, container) {
|
||||
instance.unmountComponent();
|
||||
|
||||
if (container.nodeType === DOC_NODE_TYPE) {
|
||||
container = container.documentElement;
|
||||
}
|
||||
|
||||
// http://jsperf.com/emptying-a-node
|
||||
while (container.lastChild) {
|
||||
container.removeChild(container.lastChild);
|
||||
@@ -592,6 +596,8 @@ var ReactMount = {
|
||||
|
||||
ATTR_NAME: ATTR_NAME,
|
||||
|
||||
getReactRootID: getReactRootID,
|
||||
|
||||
getID: getID,
|
||||
|
||||
setID: setID,
|
||||
|
||||
@@ -65,7 +65,7 @@ mixInto(ReactTextComponent, {
|
||||
mountDepth
|
||||
);
|
||||
return (
|
||||
'<span ' + ReactMount.ATTR_NAME + '="' + rootID + '">' +
|
||||
'<span ' + ReactMount.ATTR_NAME + '="' + escapeTextForBrowser(rootID) + '">' +
|
||||
escapeTextForBrowser(this.props.text) +
|
||||
'</span>'
|
||||
);
|
||||
|
||||
@@ -39,6 +39,66 @@ describe('rendering React components at document', function() {
|
||||
testDocument = getTestDocument();
|
||||
});
|
||||
|
||||
it('should be able to get root component id for document node', function() {
|
||||
if (!testDocument) {
|
||||
// These tests are not applicable in jst, since jsdom is buggy.
|
||||
return;
|
||||
}
|
||||
|
||||
var Root = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello World</title>
|
||||
</head>
|
||||
<body>
|
||||
Hello world
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
ReactMount.allowFullPageRender = true;
|
||||
var component = React.renderComponent(<Root />, testDocument);
|
||||
expect(testDocument.body.innerHTML).toBe(' Hello world ');
|
||||
|
||||
var componentID = ReactMount.getReactRootID(testDocument);
|
||||
expect(componentID).toBe(component._rootNodeID);
|
||||
});
|
||||
|
||||
it('should be able to unmount component from document node', function() {
|
||||
if (!testDocument) {
|
||||
// These tests are not applicable in jst, since jsdom is buggy.
|
||||
return;
|
||||
}
|
||||
|
||||
var Root = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello World</title>
|
||||
</head>
|
||||
<body>
|
||||
Hello world
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
ReactMount.allowFullPageRender = true;
|
||||
React.renderComponent(<Root />, testDocument);
|
||||
expect(testDocument.body.innerHTML).toBe(' Hello world ');
|
||||
|
||||
var unmounted = React.unmountComponentAtNode(testDocument);
|
||||
expect(unmounted).toBe(true);
|
||||
expect(testDocument.documentElement).not.toBe(null);
|
||||
expect(testDocument.documentElement.innerHTML).toBe('');
|
||||
});
|
||||
|
||||
it('should be able to switch root constructors via state', function() {
|
||||
if (!testDocument) {
|
||||
// These tests are not applicable in jst, since jsdom is buggy.
|
||||
|
||||
@@ -18,12 +18,23 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
var DOC_NODE_TYPE = 9;
|
||||
|
||||
/**
|
||||
* @param {DOMElement} container DOM element that may contain a React component
|
||||
* @param {DOMElement|DOMDocument} container DOM element that may contain
|
||||
* a React component
|
||||
* @return {?*} DOM element that may have the reactRoot ID, or null.
|
||||
*/
|
||||
function getReactRootElementInContainer(container) {
|
||||
return container && container.firstChild;
|
||||
if (!container) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (container.nodeType === DOC_NODE_TYPE) {
|
||||
return container.documentElement;
|
||||
} else {
|
||||
return container.firstChild;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = getReactRootElementInContainer;
|
||||
|
||||
@@ -147,7 +147,7 @@ var Danger = {
|
||||
|
||||
invariant(
|
||||
resultList.length === markupList.length,
|
||||
'Danger: Expected markup to render %d nodes, but rendered %d.',
|
||||
'Danger: Expected markup to render %s nodes, but rendered %s.',
|
||||
markupList.length,
|
||||
resultList.length
|
||||
);
|
||||
|
||||
@@ -57,7 +57,7 @@ var DefaultDOMPropertyConfig = {
|
||||
data: null, // For `<object />` acts as `src`.
|
||||
dateTime: MUST_USE_ATTRIBUTE,
|
||||
dir: null,
|
||||
disabled: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
|
||||
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
|
||||
draggable: null,
|
||||
encType: null,
|
||||
form: MUST_USE_ATTRIBUTE,
|
||||
|
||||
@@ -22,6 +22,7 @@ var EventConstants = require('EventConstants');
|
||||
var EventPluginHub = require('EventPluginHub');
|
||||
var EventPropagators = require('EventPropagators');
|
||||
var ExecutionEnvironment = require('ExecutionEnvironment');
|
||||
var ReactInputSelection = require('ReactInputSelection');
|
||||
var SyntheticEvent = require('SyntheticEvent');
|
||||
|
||||
var getActiveElement = require('getActiveElement');
|
||||
@@ -65,7 +66,8 @@ var mouseDown = false;
|
||||
* @param {object}
|
||||
*/
|
||||
function getSelection(node) {
|
||||
if ('selectionStart' in node) {
|
||||
if ('selectionStart' in node &&
|
||||
ReactInputSelection.hasSelectionCapabilities(node)) {
|
||||
return {
|
||||
start: node.selectionStart,
|
||||
end: node.selectionEnd
|
||||
@@ -180,14 +182,12 @@ var SelectEventPlugin = {
|
||||
activeElement = topLevelTarget;
|
||||
activeElementID = topLevelTargetID;
|
||||
lastSelection = null;
|
||||
mouseDown = false;
|
||||
}
|
||||
break;
|
||||
case topLevelTypes.topBlur:
|
||||
activeElement = null;
|
||||
activeElementID = null;
|
||||
lastSelection = null;
|
||||
mouseDown = false;
|
||||
break;
|
||||
|
||||
// Don't fire the event while the user is dragging. This matches the
|
||||
|
||||