Browse Source

Merge branch 'master' into docs-namespace-in-jsx

* master: (113 commits)
  Remove esprima-fb and use Syntax from jstransform
  Update React.renderToString argument type in docs
  [traverseAllChildren] fix out-of-scope var use.
  Use double quote for transformed `displayName` and `data-*`
  Remove unrelated comment
  Fix typo in If/Else JSX doc.
  Cleanup a couple unused variables
  Use dump cache and remove factory from ReactElement-test
  Update deprecated propTypes
  Bring in jsfiddle integration script, add harmony
  Extending period in which click events are ignored
  React.renderComponent --> React.render
  Followup fix for React.PropTypes.node
  Add comma for readability in tutorial
  Drop internal uses of .type on the class
  Drop Legacy Factories Around Classes
  Drop ReactDOM from internal DOM extensions
  Added comma to increase readability.
  Add 0.12 starter kit
  Change the date and the link url to match the proper roundup
  ...

Conflicts:
	docs/docs/02.1-jsx-in-depth.md
main
Pedro Nauck 10 years ago
parent
commit
6f17f456f5
  1. 4
      Rakefile
  2. 2
      _config.yml
  3. 71
      _data/acknowledgements.yml
  4. 6
      _data/nav_docs.yml
  5. 23
      _js/examples/hello.js
  6. 70
      _js/examples/markdown.js
  7. 51
      _js/examples/timer.js
  8. 80
      _js/examples/todo.js
  9. 25
      _js/html-jsx.js
  10. 11
      _js/jsfiddle-integration.js
  11. 9
      _js/jsx-compiler.js
  12. 9
      _js/live_editor.js
  13. 5
      _layouts/default.html
  14. 2
      _posts/2013-11-05-thinking-in-react.md
  15. 46
      _posts/2014-09-16-react-v0.11.2.md
  16. 222
      _posts/2014-10-14-introducing-react-elements.md
  17. 150
      _posts/2014-10-16-react-v0.12-rc1.md
  18. 152
      _posts/2014-10-17-community-roundup-23.md
  19. 15
      _posts/2014-10-27-react-js-conf.md
  20. 127
      _posts/2014-10-28-react-v0.12.md
  21. 48
      docs/02-displaying-data.md
  22. 8
      docs/02-displaying-data.zh-CN.md
  23. 158
      docs/02.1-jsx-in-depth.md
  24. 71
      docs/02.2-jsx-spread.md
  25. 2
      docs/02.3-jsx-gotchas.md
  26. 8
      docs/03-interactivity-and-dynamic-uis.md
  27. 8
      docs/04-multiple-components.md
  28. 31
      docs/05-reusable-components.md
  29. 159
      docs/06-transferring-props.md
  30. 2
      docs/07-forms.md
  31. 4
      docs/08-working-with-the-browser.md
  32. 0
      docs/08.1-more-about-refs.md
  33. 2
      docs/09-tooling-integration.md
  34. 0
      docs/10-addons.md
  35. 33
      docs/10.1-animation.md
  36. 14
      docs/10.2-form-input-binding-sugar.md
  37. 0
      docs/10.3-class-name-manipulation.md
  38. 6
      docs/10.4-test-utils.md
  39. 8
      docs/10.5-clone-with-props.md
  40. 0
      docs/10.6-update.md
  41. 0
      docs/10.7-pure-render-mixin.md
  42. 0
      docs/10.8-perf.md
  43. 18
      docs/getting-started.md
  44. 19
      docs/getting-started.zh-CN.md
  45. 42
      docs/ref-01-top-level-api.md
  46. 37
      docs/ref-02-component-api.md
  47. 16
      docs/ref-04-tags-and-attributes.md
  48. 1
      docs/ref-08-reconciliation.md
  49. 192
      docs/ref-09-glossary.md
  50. 4
      docs/thinking-in-react.md
  51. 24
      docs/tutorial.md
  52. 2
      downloads.md
  53. BIN
      downloads/react-0.11.2.zip
  54. BIN
      downloads/react-0.12.0-rc1.zip
  55. BIN
      downloads/react-0.12.0.zip
  56. BIN
      img/blog/flux-chart.png
  57. BIN
      img/blog/reflux-flux.png
  58. 4
      tips/02-inline-styles.md
  59. 26
      tips/03-if-else-in-JSX.md
  60. 4
      tips/06-style-props-value-px.md
  61. 8
      tips/07-children-props-type.md
  62. 6
      tips/08-controlled-input-null-value.md
  63. 12
      tips/10-props-in-getInitialState-as-anti-pattern.md
  64. 4
      tips/11-dom-event-listeners.md
  65. 4
      tips/12-initial-ajax.md
  66. 9
      tips/13-false-in-jsx.md
  67. 4
      tips/14-communicate-between-components.md
  68. 4
      tips/15-expose-component-functions.md
  69. 14
      tips/16-references-to-components.md
  70. 4
      tips/17-children-undefined.md

4
Rakefile

@ -4,12 +4,12 @@ require('yaml')
desc "generate js from jsx"
task :js do
system "../bin/jsx _js js"
system "../bin/jsx --harmony _js js"
end
desc "watch js"
task :watch do
Process.spawn "../bin/jsx --watch _js js"
Process.spawn "../bin/jsx --watch --harmony _js js"
Process.waitall
end

2
_config.yml

@ -34,4 +34,4 @@ sass:
sass_dir: _css
gems:
- jekyll-redirect-from
react_version: 0.11.1
react_version: 0.11.2

71
_data/acknowledgements.yml

@ -1,22 +1,30 @@
---
- - Adam Krebs
- Adam Mark
- Adam Solove
- Alan deLevie
- Alex Zelenskiy
- Alexander Solovyov
- Alexey Raspopov
- Andre Z Sanchez
- Andreas Svensson
- Andres Suarez
- Andrew Davey
- Andrew Rasmussen
- Andrew Zich
- Andrey Popp
- Anthony van der Hoorn
- Areeb Malik
- Ayman Osman
- Ben Alpert
- Ben Foxall
- Ben Newman
- Ben Ripkens
- Bill Fisher
- Bob Eagan
- Bojan Mihelac
- Brandon Bloom
- Brandon Tilley
- Brian Cooke
- Brian Kim
- Brian Reavis
@ -24,12 +32,17 @@
- Cam Spiers
- Cassus Adam Banko
- Cat Chen
- Charles Marsh
- Cheng Lou
- Chris Sciolla
- Christian Alfoni
- Christian Roman
- Christoph Pojer
- Christopher Monsanto
- Clay Allsopp
- Connor McSheffrey
- Cotton Hou
- Dan Abramov
- Dan Schafer
- Daniel Gasienica
- Daniel Lo Nigro
@ -40,6 +53,7 @@
- David Hellsing
- David Hu
- Devon Blandin
- Dmitrii Abramov
- Dmitry Mazuro
- Dustin Getz
- Enguerran
@ -49,21 +63,24 @@
- Evan Coonrod
- Fabio M. Costa
- Felipe Oliveira Carvalho
- Felix Gnass
- Felix Kling
- Fernando Correia
- François-Xavier Bois
- Fred Zhao
- G Scott Olson
- Garren Smith
- Geert Pasteels
- Geert-Jan Brits
- George A Sisco III
- Gilbert
- Glen Mailer
- Greg Hurrell
- - Greg Roodt
- Greg Roodt
- Guangqiang Dong
- Guido Bouman
- Harry Hull
- Harshad Sabne
- - Harshad Sabne
- Hendrik Swanepoel
- Hugo Jobling
- Ian Obermiller
@ -71,25 +88,36 @@
- Irae Carvalho
- Isaac Salier-Hellendag
- Ivan Kozik
- Ivan Vergiliev
- Jacob Gable
- Jacob Greenleaf
- Jaime Mingo
- Jakub Malinowski
- James Brantly
- James Ide
- James Seppi
- Jamie Wong
- Jamison Dance
- Jan Hancic
- Jan Kassens
- Jared Forsyth
- Jason Bonta
- Jason Trill
- Jean Lauliac
- Jed Watson
- Jeff Barczewski
- Jeff Carpenter
- Jeff Chan
- Jeff Morrison
- Jeff Welch
- Jeffrey Lin
- Jesse Skinner
- Jignesh Kakadiya
- Jim OBrien
- Jimmy Jea
- Jing Chen
- Johannes Baiter
- Johannes Emerich
- John Watson
- Jon Beebe
- Jonas Enlund
@ -101,15 +129,18 @@
- Josh Yudaken
- Joshua Ma
- Julen Ruiz Aizpuru
- Julien Bordellier
- Jun Wu
- Juraj Dudak
- Justin Jaffray
- Karl Mikkelsen
- Karpich Dmitry
- Keito Uchiyama
- Kit Randel
- Kunal Mehta
- Kyle Mathews
- Laurence Rowe
- Lee Byron
- Levi McCallum
- Lily
- Logan Allen
@ -117,23 +148,40 @@
- Marcin Kwiatkowski
- Marcin Szczepanski
- Mariano Desanze
- Mark Anderson
- Mark Hintz
- Mark IJbema
- Mark Richardson
- Marshall Roch
- - Martin Andert
- Martin Andert
- Martin Konicek
- Mathieu M-Gosselin
- Matt Harrison
- Matthew Dapena-Tretter
- Matti Nelimarkka
- Max F. Albrecht
- Michael Chan
- - Michael Randers-Pehrson
- Michal Srb
- Mike D Pilsbury
- Miorel Palii
- Mouad Debbar
- Nadeesha Cabral
- Naman Goel
- Nate Hunzaker
- Nathan White
- Nicholas Bergson-Shilcock
- Nick Fitzgerald
- Nick Gavalas
- Nick Merwin
- Nick Thompson
- Nick Williams
- Niklas Boström
- Oleg
- Oleksii Markhovskyi
- Oliver Zeigermann
- Owen Coutts
- Pablo Lacerda de Miranda
- Pascal Hartig
- Paul O’Shannessy
- Paul Seiffert
@ -148,32 +196,49 @@
- Richard D. Worth
- Richard Feldman
- Richard Livesey
- Rick Beerendonk
- Rob Arnold
- Ryan Seddon
- Sahat Yalkabov
- Sam Selikoff
- Sander Spies
- Sean Kinsey
- Sebastian Markbåge
- Sergey Generalov
- Shane O'Sullivan
- Shaun Trennery
- Sheraz
- Shripad K
- Simon Højberg
- Simon Welsh
- Stefan Dombrowski
- Stephen Murphy
- Stoyan Stefanov
- Sundeep Malladi
- Sunny Juneja
- Sven Helmberger
- Sébastien Lorber
- Thomas Aylott
- Thomas Boyt
- Thomas Shaddox
- Thomas Shafer
- ThomasCrvsr
- Timothy Yung
- Tom Haggie
- Tom Hauburger
- Tom MacWright
- Tom Occhino
- Ville Immonen
- Vjeux
- Volkan Unsal
- Wayne Larsen
- WickyNilliams
- Wincent Colaiuta
- XuefengWu
- Yuriy Dybskiy
- Yuval Dekel
- Zach Bruggeman
- cutbko
- davidxi
- imagentleman
- jon madison

6
_data/nav_docs.yml

@ -23,6 +23,8 @@
subitems:
- id: jsx-in-depth
title: JSX in Depth
- id: jsx-spread
title: JSX Spread Attributes
- id: jsx-gotchas
title: JSX Gotchas
- id: interactivity-and-dynamic-uis
@ -31,6 +33,8 @@
title: Multiple Components
- id: reusable-components
title: Reusable Components
- id: transferring-props
title: Transferring Props
- id: forms
title: Forms
- id: working-with-the-browser
@ -77,6 +81,8 @@
title: Special Non-DOM Attributes
- id: reconciliation
title: Reconciliation
- id: glossary
title: React (Virtual) DOM Terminology
- title: Flux
items:
- id: flux-overview

23
_js/examples/hello.js

@ -1,19 +1,14 @@
/**
* @jsx React.DOM
*/
var HELLO_COMPONENT = `
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
var HELLO_COMPONENT = "\
/** @jsx React.DOM */\n\
var HelloMessage = React.createClass({\n\
render: function() {\n\
return <div>Hello {this.props.name}</div>;\n\
}\n\
});\n\
\n\
React.renderComponent(<HelloMessage name=\"John\" />, mountNode);\
";
React.render(<HelloMessage name="John" />, mountNode);
`;
React.renderComponent(
React.render(
<ReactPlayground codeText={HELLO_COMPONENT} />,
document.getElementById('helloExample')
);

70
_js/examples/markdown.js

@ -1,43 +1,37 @@
/**
* @jsx React.DOM
*/
var MARKDOWN_COMPONENT = `
var converter = new Showdown.converter();
var MARKDOWN_COMPONENT = "\
/** @jsx React.DOM */\n\
\n\
var converter = new Showdown.converter();\n\
\n\
var MarkdownEditor = React.createClass({\n\
getInitialState: function() {\n\
return {value: 'Type some *markdown* here!'};\n\
},\n\
handleChange: function() {\n\
this.setState({value: this.refs.textarea.getDOMNode().value});\n\
},\n\
render: function() {\n\
return (\n\
<div className=\"MarkdownEditor\">\n\
<h3>Input</h3>\n\
<textarea\n\
onChange={this.handleChange}\n\
ref=\"textarea\"\n\
defaultValue={this.state.value} />\n\
<h3>Output</h3>\n\
<div\n\
className=\"content\"\n\
dangerouslySetInnerHTML={{\n\
__html: converter.makeHtml(this.state.value)\n\
}}\n\
/>\n\
</div>\n\
);\n\
}\n\
});\n\
\n\
React.renderComponent(<MarkdownEditor />, mountNode);\
";
var MarkdownEditor = React.createClass({
getInitialState: function() {
return {value: 'Type some *markdown* here!'};
},
handleChange: function() {
this.setState({value: this.refs.textarea.getDOMNode().value});
},
render: function() {
return (
<div className="MarkdownEditor">
<h3>Input</h3>
<textarea
onChange={this.handleChange}
ref="textarea"
defaultValue={this.state.value} />
<h3>Output</h3>
<div
className="content"
dangerouslySetInnerHTML={{
__html: converter.makeHtml(this.state.value)
}}
/>
</div>
);
}
});
React.renderComponent(
React.render(<MarkdownEditor />, mountNode);
`;
React.render(
<ReactPlayground codeText={MARKDOWN_COMPONENT} />,
document.getElementById('markdownExample')
);

51
_js/examples/timer.js

@ -1,33 +1,28 @@
/**
* @jsx React.DOM
*/
var TIMER_COMPONENT = `
var Timer = React.createClass({
getInitialState: function() {
return {secondsElapsed: 0};
},
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render: function() {
return (
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>
);
}
});
var TIMER_COMPONENT = "\
/** @jsx React.DOM */\n\
var Timer = React.createClass({\n\
getInitialState: function() {\n\
return {secondsElapsed: 0};\n\
},\n\
tick: function() {\n\
this.setState({secondsElapsed: this.state.secondsElapsed + 1});\n\
},\n\
componentDidMount: function() {\n\
this.interval = setInterval(this.tick, 1000);\n\
},\n\
componentWillUnmount: function() {\n\
clearInterval(this.interval);\n\
},\n\
render: function() {\n\
return (\n\
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>\n\
);\n\
}\n\
});\n\
\n\
React.renderComponent(<Timer />, mountNode);\
";
React.render(<Timer />, mountNode);
`;
React.renderComponent(
React.render(
<ReactPlayground codeText={TIMER_COMPONENT} />,
document.getElementById('timerExample')
);

80
_js/examples/todo.js

@ -1,47 +1,43 @@
/**
* @jsx React.DOM
*/
var TODO_COMPONENT = `
var TodoList = React.createClass({
render: function() {
var createItem = function(itemText) {
return <li>{itemText}</li>;
};
return <ul>{this.props.items.map(createItem)}</ul>;
}
});
var TodoApp = React.createClass({
getInitialState: function() {
return {items: [], text: ''};
},
onChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var nextItems = this.state.items.concat([this.state.text]);
var nextText = '';
this.setState({items: nextItems, text: nextText});
},
render: function() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.onChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
);
}
});
var TODO_COMPONENT = "\
/** @jsx React.DOM */\n\
var TodoList = React.createClass({\n\
render: function() {\n\
var createItem = function(itemText) {\n\
return <li>{itemText}</li>;\n\
};\n\
return <ul>{this.props.items.map(createItem)}</ul>;\n\
}\n\
});\n\
var TodoApp = React.createClass({\n\
getInitialState: function() {\n\
return {items: [], text: ''};\n\
},\n\
onChange: function(e) {\n\
this.setState({text: e.target.value});\n\
},\n\
handleSubmit: function(e) {\n\
e.preventDefault();\n\
var nextItems = this.state.items.concat([this.state.text]);\n\
var nextText = '';\n\
this.setState({items: nextItems, text: nextText});\n\
},\n\
render: function() {\n\
return (\n\
<div>\n\
<h3>TODO</h3>\n\
<TodoList items={this.state.items} />\n\
<form onSubmit={this.handleSubmit}>\n\
<input onChange={this.onChange} value={this.state.text} />\n\
<button>{'Add #' + (this.state.items.length + 1)}</button>\n\
</form>\n\
</div>\n\
);\n\
}\n\
});\n\
React.renderComponent(<TodoApp />, mountNode);\
";
React.render(<TodoApp />, mountNode);
`;
React.renderComponent(
React.render(
<ReactPlayground codeText={TODO_COMPONENT} />,
document.getElementById('todoExample')
);

25
_js/html-jsx.js

@ -1,23 +1,14 @@
/**
* Copyright 2013-2014 Facebook, Inc.
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @jsx React.DOM
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* This is a web interface for the HTML to JSX converter contained in
* This is a web interface for the HTML to JSX converter contained in
* `html-jsx-lib.js`.
*/
;(function() {
@ -87,5 +78,5 @@ var HELLO_COMPONENT = "\
}
});
React.renderComponent(<HTMLtoJSXComponent />, document.getElementById('jsxCompiler'));
}());
React.render(<HTMLtoJSXComponent />, document.getElementById('jsxCompiler'));
}());

11
_js/jsfiddle-integration.js

@ -0,0 +1,11 @@
(function() {
var tag = document.querySelector(
'script[type="application/javascript;version=1.7"]'
);
if (!tag || tag.textContent.indexOf('window.onload=function(){') !== -1) {
alert('Bad JSFiddle configuration, please fork the original React JSFiddle');
}
tag.setAttribute('type', 'text/jsx;harmony=true');
tag.textContent = tag.textContent.replace(/^\/\/<!\[CDATA\[/, '');
})();

9
_js/jsx-compiler.js

@ -1,16 +1,11 @@
/**
* @jsx React.DOM
*/
var HELLO_COMPONENT = "\
/** @jsx React.DOM */\n\
var HelloMessage = React.createClass({\n\
render: function() {\n\
return <div>Hello {this.props.name}</div>;\n\
}\n\
});\n\
\n\
React.renderComponent(<HelloMessage name=\"John\" />, mountNode);\
React.render(<HelloMessage name=\"John\" />, mountNode);\
";
function transformer(harmony, code) {
@ -44,7 +39,7 @@ var CompilerPlayground = React.createClass({
);
},
});
React.renderComponent(
React.render(
<CompilerPlayground />,
document.getElementById('jsxCompiler')
);

9
_js/live_editor.js

@ -1,8 +1,3 @@
/**
* @jsx React.DOM
*/
var IS_MOBILE = (
navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
@ -195,7 +190,7 @@ var ReactPlayground = React.createClass({
try {
var compiledCode = this.compileCode();
if (this.props.renderCode) {
React.renderComponent(
React.render(
<CodeMirrorEditor codeText={compiledCode} readOnly={true} />,
mountNode
);
@ -204,7 +199,7 @@ var ReactPlayground = React.createClass({
}
} catch (err) {
this.setTimeout(function() {
React.renderComponent(
React.render(
<div className="playgroundError">{err.toString()}</div>,
mountNode
);

5
_layouts/default.html

@ -78,7 +78,10 @@
A Facebook &amp; Instagram collaboration.<br>
<a href="/react/acknowledgements.html">Acknowledgements</a>
</div>
<div class="right">&copy; 2014 Facebook Inc.</div>
<div class="right">
&copy; 2013&ndash;2014 Facebook Inc.<br>
Documentation licensed under <a href="http://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.
</div>
</footer>
</div>
<div id="fb-root"></div>

2
_posts/2013-11-05-thinking-in-react.md

@ -3,7 +3,7 @@ title: "Thinking in React"
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.
React is, in my opinion, the premier way to build big, fast Web apps with JavaScript. It has 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.

46
_posts/2014-09-16-react-v0.11.2.md

@ -0,0 +1,46 @@
---
title: React v0.11.2
author: Paul O’Shannessy
---
Today we're releasing React v0.11.2 to add a few small features.
We're adding support for two more DOM elements, `<dialog>` and `<picture>`, as well as the associated attributes needed to use these elements: `open`, `media`, and `sizes`. While not all browsers support these natively, some of our cutting edge users want to make use of them, so we're making them available to everybody.
We're also doing some work to prepare for v0.12 and improve compatibility between the versions. To do this we are replacing `React.createDescriptor` with `React.createElement`. `createDescriptor` will continue to work with a warning and will be gone in v0.12. Chances are that this won't affect anybody.
And lastly, on the heels of announcing Flow at [@Scale](http://atscaleconference.com/) yesterday, we're adding the ability to strip TypeScript-like type annotations as part of the `jsx` transform. To use, simply use the `--strip-types` flag on the command line, or set `stripTypes` in the `options` object when calling the API. We'll be talking about Flow more in the coming months. But for now, it's helpful to know that it is a flow-sensitive JavaScript type checker we will be open sourcing soon.
The release is available for download from the CDN:
* **React**
Dev build with warnings: <http://fb.me/react-0.11.2.js>
Minified build for production: <http://fb.me/react-0.11.2.min.js>
* **React with Add-Ons**
Dev build with warnings: <http://fb.me/react-with-addons-0.11.2.js>
Minified build for production: <http://fb.me/react-with-addons-0.11.2.min.js>
* **In-Browser JSX transformer**
<http://fb.me/JSXTransformer-0.11.2.js>
We've also published version `0.11.2` of the `react` and `react-tools` packages on npm and the `react` package on bower.
Please try these builds out and [file an issue on GitHub](https://github.com/facebook/react/issues/new) if you see anything awry.
### React Core
#### New Features
* Added support for `<dialog>` element and associated `open` attribute
* Added support for `<picture>` element and associated `media` and `sizes` attributes
* Added `React.createElement` API in preparation for React v0.12
* `React.createDescriptor` has been deprecated as a result
### JSX
* `<picture>` is now parsed into `React.DOM.picture`
### React Tools
* Update `esprima` and `jstransform` for correctness fixes
* The `jsx` executable now exposes a `--strip-types` flag which can be used to remove TypeScript-like type annotations
* This option is also exposed to `require('react-tools').transform` as `stripTypes`

222
_posts/2014-10-14-introducing-react-elements.md

@ -0,0 +1,222 @@
---
title: "Introducing React Elements"
author: Sebastian Markbåge
redirect_from: "blog/2014/10/14/introducting-react-elements.html"
---
The upcoming React 0.12 tweaks some APIs to get us close to the final 1.0 API. This release is all about setting us up for making the `ReactElement` type really FAST, [jest unit testing](http://facebook.github.io/jest/) easier, making classes simpler (in preparation for ES6 classes) and better integration with third-party languages!
If you currently use JSX everywhere, you don't really have to do anything to get these benefits! The updated transformer will do it for you.
If you can't or don't want to use JSX, then please insert some hints for us. Add a `React.createFactory` call around your imported class when you require it:
```javascript
var MyComponent = React.createFactory(require('MyComponent'));
```
Everything is backwards compatible for now, and as always React will provide you with descriptive console messaging to help you upgrade.
`ReactElement` is the primary API of React. Making it faster has shown to give us several times faster renders on common benchmarks. The API tweaks in this release helps us get there.
Continue reading if you want all the nitty gritty details...
## New Terminology
We wanted to make it easier for new users to see the parallel with the DOM (and why React is different). To align our terminology we now use the term `ReactElement` instead of _descriptor_. Likewise, we use the term `ReactNode` instead of _renderable_.
[See the full React terminology guide.](https://gist.github.com/sebmarkbage/fcb1b6ab493b0c77d589)
## Creating a ReactElement
We now expose an external API for programmatically creating a `ReactElement` object.
```javascript
var reactElement = React.createElement(type, props, children);
```
The `type` argument is either a string (HTML tag) or a class. It's a description of what tag/class is going to be rendered and what props it will contain. You can also create factory functions for specific types. This basically just provides the type argument for you:
```javascript
var div = React.createFactory('div');
var reactDivElement = div(props, children);
```
## Deprecated: Auto-generated Factories
Imagine if `React.createClass` was just a plain JavaScript class. If you call a class as a plain function you would call the component's constructor to create a Component instance, not a `ReactElement`:
```javascript
new MyComponent(); // Component, not ReactElement
```
React 0.11 gave you a factory function for free when you called `React.createClass`. This wrapped your internal class and then returned a `ReactElement` factory function for you.
```javascript
var MyComponent = React.createFactory(
class {
render() {
...
}
}
);
```
In future versions of React, we want to be able to support pure classes without any special React dependencies. To prepare for that we're [deprecating the auto-generated factory](https://gist.github.com/sebmarkbage/d7bce729f38730399d28).
This is the biggest change to 0.12. Don't worry though. This functionality continues to work the same for this release, it just warns you if you're using a deprecated API. That way you can upgrade piece-by-piece instead of everything at once.
## Upgrading to 0.12
### React With JSX
If you use the React specific [JSX](http://facebook.github.io/jsx/) transform, the upgrade path is simple. Just make sure you have React in scope.
```javascript
// If you use node/browserify modules make sure
// that you require React into scope.
var React = require('react');
```
React's JSX will create the `ReactElement` for you. You can continue to use JSX with regular classes:
```javascript
var MyComponent = React.createClass(...);
var MyOtherComponent = React.createClass({
render: function() {
return <MyComponent prop="value" />;
}
});
```
*NOTE: React's JSX will not call arbitrary functions in future releases. This restriction is introduced so that it's easier to reason about the output of JSX by both the reader of your code and optimizing compilers. The JSX syntax is not tied to React. Just the transpiler. You can still use [the JSX spec](http://facebook.github.io/jsx/) with a different transpiler for custom purposes.*
### React Without JSX
If you don't use JSX and just call components as functions, you will need to explicitly create a factory before calling it:
```javascript
var MyComponentClass = React.createClass(...);
var MyComponent = React.createFactory(MyComponentClass); // New step
var MyOtherComponent = React.createClass({
render: function() {
return MyComponent({ prop: 'value' });
}
});
```
If you're using a module system, the recommended solution is to export the class and create the factory on the requiring side.
Your class creation is done just like before:
```javascript
// MyComponent.js
var React = require('react');
var MyComponent = React.createClass(...);
module.exports = MyComponent;
```
The other side uses `React.createFactory` after `require`ing the component class:
```javascript
// MyOtherComponent.js
var React = require('react');
// All you have to do to upgrade is wrap your requires like this:
var MyComponent = React.createFactory(require('MyComponent'));
var MyOtherComponent = React.createClass({
render: function() {
return MyComponent({ prop: 'value' });
}
});
module.exports = MyOtherComponent;
```
You ONLY have to do this for custom classes. React still has built-in factories for common HTML elements.
```javascript
var MyDOMComponent = React.createClass({
render: function() {
return React.DOM.div({ className: 'foo' }); // still ok
}
});
```
We realize that this is noisy. At least it's on the top of the file (out of sight, out of mind). This a tradeoff we had to make to get [the other benefits](https://gist.github.com/sebmarkbage/d7bce729f38730399d28) that this model unlocks.
### Anti-Pattern: Exporting Factories
If you have an isolated project that only you use, then you could create a helper that creates both the class and the factory at once:
```javascript
// Anti-pattern - Please, don't use
function createClass(spec) {
return React.createFactory(React.createClass(spec));
}
```
This makes your components incompatible with jest testing, consumers using JSX, third-party languages that implement their own optimized `ReactElement` creation, etc.
It also encourages you to put more logic into these helper functions. Something that another language, a compiler or a reader of your code couldn't reason about.
To fit into the React ecosystem we recommend that you always export pure classes from your shared modules and let the consumer decide the best strategy for generating `ReactElement`s.
## Third-party Languages
The signature of a `ReactElement` is something like this:
```javascript
{
type : string | class,
props : { children, className, etc. },
key : string | boolean | number | null,
ref : string | null
}
```
Languages with static typing that don't need validation (e.g. [Om in ClojureScript](https://github.com/swannodette/om)), and production level compilers will be able to generate these objects inline instead of going through the validation step. This optimization will allow significant performance improvements in React.
## Your Thoughts and Ideas
We'd love to hear your feedback on this API and your preferred style. A plausible alternative could be to directly inline objects instead of creating factory functions:
```javascript
// MyOtherComponent.js
var React = require('react');
var MyComponent = require('MyComponent');
var MyOtherComponent = React.createClass({
render: function() {
return { type: MyComponent, props: { prop: 'value' } };
}
});
module.exports = MyOtherComponent;
```
This moves the noise down into the render method though. It also doesn't provide a hook for dynamic validation/type checking so you'll need some other way to verify that it's safe.
*NOTE: This won't work in this version of React because it's conflicting with other legacy APIs that we're deprecating. (We temporarily add a `element._isReactElement = true` marker on the object.)*
## The Next Step: ES6 Classes
After 0.12 we'll begin work on moving to ES6 classes. We will still support `React.createClass` as a backwards compatible API. If you use an ES6 transpiler you will be able to declare your components like this:
```javascript
export class MyComponent {
render() {
...
}
};
```
This upcoming release is a stepping stone to make it as easy as this. Thanks for your support.

150
_posts/2014-10-16-react-v0.12-rc1.md

@ -0,0 +1,150 @@
---
title: "React v0.12 RC"
author: Sebastian Markbåge
---
We are finally ready to share the work we've been doing over the past couple months. A lot has gone into this and we want to make sure we iron out any potential issues before we make this final. So, we're shipping a Release Candidate for React v0.12 today. If you get a chance, please give it a try and report any issues you find! A full changelog will accompany the final release but we've highlighted the interesting and breaking changes below.
The release candidate is available for download:
* **React**
Dev build with warnings: <http://fb.me/react-0.12.0-rc1.js>
Minified build for production: <http://fb.me/react-0.12.0-rc1.min.js>
* **React with Add-Ons**
Dev build with warnings: <http://fb.me/react-with-addons-0.12.0-rc1.js>
Minified build for production: <http://fb.me/react-with-addons-0.12.0-rc1.min.js>
* **In-Browser JSX transformer**
<http://fb.me/JSXTransformer-0.12.0-rc1.js>
We've also published version `0.12.0-rc1` of the `react` and `react-tools` packages on npm and the `react` package on bower.
## React Elements
The biggest conceptual change we made in v0.12 is the move to React Elements. [We talked about this topic in depth earlier this week](/react/blog/2014/10/14/introducting-react-elements.html). If you haven't already, you should read up on the exciting changes in there!
## JSX Changes
Earlier this year we decided to write [a specification for JSX](http://facebook.github.io/jsx/). This has allowed us to make some changes focused on the React specific JSX and still allow others to innovate in the same space.
### The `@jsx` Pragma is Gone!
We have wanted to do this since before we even open sourced React. No more `/** @jsx React.DOM */`!. The React specific JSX transform assumes you have `React` in scope (which had to be true before anyway).
`JSXTransformer` and `react-tools` have both been updated to account for this.
### JSX for Function Calls is No Longer Supported
The React specific JSX transform no longer transforms to function calls. Instead we use `React.createElement` and pass it arguments. This allows us to make optimizations and better support React as a compile target for things like Om. Read more in the [React Elements introduction](/react/blog/2014/10/14/introducting-react-elements.html).
The result of this change is that we will no longer support arbitrary function calls. We understand that the ability to do was was a convenient shortcut for many people but we believe the gains will be worth it.
### JSX Lower-case Convention
We used to have a whitelist of HTML tags that got special treatment in JSX. However as new HTML tags got added to the spec, or we added support for more SVG tags, we had to go update our whitelist. Additionally, there was ambiguity about the behavior. There was always the chance that something new added to the tag list would result in breaking your code. For example:
```javascript
return <component />;
```
Is `component` an existing HTML tag? What if it becomes one?
To address this, we decided on a convention: __All JSX tags that start with a lower-case letter or contain a dash are treated as HTML.__
This means that you no longer have to wait for us to upgrade JSX to use new tags. This also introduces the possibility to consume custom elements (Web Components) - although custom attributes are not yet fully supported.
Currently we still use the whitelist as a sanity check. The transform will fail when it encounters an unknown tag. This allows you to update your code without hitting errors in production.
In addition, the HTML tags are converted to strings instead of using `React.DOM` directly. `<div/>` becomes `React.createElement('div')` instead of `React.DOM.div()`.
### JSX Spread Attributes
Previously there wasn't a way to for you to pass a dynamic or unknown set of properties through JSX. This is now possible using the spread `...` operator.
```javascript
var myProps = { a: 1, b: 2 };
return <MyComponent {...myProps} />;
```
This merges the properties of the object onto the props of `MyComponent`.
[Read More About Spread Attributes](https://gist.github.com/sebmarkbage/07bbe37bc42b6d4aef81)
If you used to use plain function calls to pass arbitrary props objects...
```javascript
return MyComponent(myProps);
```
You can now switch to using Spread Attributes instead:
```javascript
return <MyComponent {...myProps} />;
```
## Breaking Change: `key` and `ref` Removed From `this.props`
The props `key` and `ref` were already reserved property names. This turned out to be difficult to explicitly statically type since any object can accept these extra props. It also screws up JIT optimizations of React internals in modern VMs.
These are concepts that React manages from outside the Component before it even gets created so it shouldn't be part of the props.
We made this distinction clearer by moving them off the props object and onto the `ReactElement` itself. This means that you need to rename:
`someElement.props.key` -> `someElement.key`
You can no longer access `this.props.ref` and `this.props.key` from inside the Component instance itself. So you need to use a different name for those props.
You do NOT need to change the way to define `key` and `ref`, only if you need to read it. E.g. `<div key="my-key" />` and `div({ key: 'my-key' })` still works.
## Breaking Change: Default Props Resolution
This is a subtle difference but `defaultProps` are now resolved at `ReactElement` creation time instead of when it's mounted. This is means that we can avoid allocating an extra object for the resolved props.
You will primarily see this breaking if you're also using `transferPropsTo`.
## Deprecated: transferPropsTo
`transferPropsTo` is deprecated in v0.12 and will be removed in v0.13. This helper function was a bit magical. It auto-merged a certain whitelist of properties and excluded others. It was also transferring too many properties. This meant that we have to keep a whitelist of valid HTML attributes in the React runtime. It also means that we can't catch typos on props.
Our suggested solution is to use the Spread Attributes.
```javascript
return <div {...this.props} />;
```
Or, just if you're not using JSX:
```javascript
return div(this.props);
```
Although to avoid passing too many props down, you'll probably want to use something like ES7 rest properties. [Read more about upgrading from transferPropsTo](https://gist.github.com/sebmarkbage/a6e220b7097eb3c79ab7).
## Deprecated: Returning `false` in Event Handlers
It used to be possible to return `false` from event handlers to preventDefault. We did this because this works in most browsers. This is a confusing API and we might want to use the return value for something else. Therefore, this is deprecated. Use `event.preventDefault()` instead.
## Renamed APIs
As part of the [new React terminology](https://gist.github.com/sebmarkbage/fcb1b6ab493b0c77d589) we aliased some existing APIs to use the new naming convention:
- `React.renderComponent` -> `React.render`
- `React.renderComponentToString` -> `React.renderToString`
- `React.renderComponentToStaticMarkup` -> `React.renderToStaticMarkup`
- `React.isValidComponent` -> `React.isValidElement`
- `React.PropTypes.component` -> `React.PropTypes.element`
- `React.PropTypes.renderable` -> `React.PropTypes.node`
The older APIs will log a warning but work the same. They will be removed in v0.13.

152
_posts/2014-10-17-community-roundup-23.md

@ -0,0 +1,152 @@
---
title: "Community Round-up #23"
layout: post
author: Lou Husson
---
This round-up is a special edition on [Flux](http://facebook.github.io/flux/). If you expect to see diagrams showing arrows that all point in the same direction, you won't be disappointed!
## React And Flux at ForwardJS
Facebook engineers [Jing Chen](https://github.com/jingc) and [Bill Fisher](https://github.com/fisherwebdev) gave a talk about Flux and React at [ForwardJS](http://forwardjs.com/), and how using an application architecture with a unidirectional data flow helped solve recurring bugs.
<iframe width="650" height="315" src="//www.youtube.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe>
# Yahoo
Yahoo is converting Yahoo Mail to React and Flux and in the process, they open sourced several components. This will help you get an isomorphic application up and running.
- [Flux Router Component](https://github.com/yahoo/flux-router-component)
- [Dispatchr](https://github.com/yahoo/dispatchr)
- [Fetchr](https://github.com/yahoo/fetchr)
- [Flux Examples](https://github.com/yahoo/flux-examples)
## Reflux
[Mikael Brassman](http://spoike.ghost.io/) wrote [Reflux](https://github.com/spoike/refluxjs), a library that implements Flux concepts. Note that it diverges significantly from the way we use Flux at Facebook. He explains [the reasons why in a blog post](http://spoike.ghost.io/deconstructing-reactjss-flux/).
<center>
<a href="http://spoike.ghost.io/deconstructing-reactjss-flux/"><img src="/react/img/blog/reflux-flux.png" width="400" /></a>
</center>
## React and Flux Interview
[Ian Obermiller](http://ianobermiller.com/), engineer at Facebook, [made a lengthy interview](http://ianobermiller.com/blog/2014/09/15/react-and-flux-interview/) on the experience of using React and Flux in order to build probably the biggest React application ever written so far.
> I’ve actually said this many times to my team too, I love React. It’s really great for making these complex applications. One thing that really surprised me with it is that React combined with a sane module system like CommonJS, and making sure that you actually modulize your stuff properly has scaled really well to a team of almost 10 developers working on hundreds of files and tens of thousands of lines of code.
>
> Really, a fairly large code base... stuff just works. You don’t have to worry about mutating, and the state of the DOM just really makes stuff easy. Just conceptually it’s easier just to think about here’s what I have, here’s my data, here’s how it renders, I don’t care about anything else. For most cases that is really simplifying and makes it really fast to do stuff.
>
> [Read the full interview...](http://ianobermiller.com/blog/2014/09/15/react-and-flux-interview/)
## Adobe's Brackets Project Tree
[Kevin Dangoor](http://www.kevindangoor.com/) is converting the project tree of [Adobe's Bracket text editor](http://brackets.io/) to React and Flux. He wrote about his experience [using Flux](http://www.kevindangoor.com/2014/09/intro-to-the-new-brackets-project-tree/).
<center>
<a href="http://www.kevindangoor.com/2014/09/intro-to-the-new-brackets-project-tree/"><img src="/react/img/blog/flux-diagram.png" width="400" /></a>
</center>
## Async Requests with Flux Revisited
[Reto Schläpfer](http://www.code-experience.com/the-code-experience/) came back to a Flux project he hasn't worked on for a month and [saw many ways to improve the way he implemented Flux](http://www.code-experience.com/async-requests-with-react-js-and-flux-revisited/). He summarized his learnings in a blog post.
> The smarter way is to call the Web Api directly from an Action Creator and then make the Api dispatch an event with the request result as a payload. The Store(s) can choose to listen on those request actions and change their state accordingly.
>
> Before I show some updated code snippets, let me explain why this is superior:
>
> - There should be only one channel for all state changes: The Dispatcher. This makes debugging easy because it just requires a single console.log in the dispatcher to observe every single state change trigger.
>
> - Asynchronously executed callbacks should not leak into Stores. The consequences of it are just to hard to fully foresee. This leads to elusive bugs. Stores should only execute synchronous code. Otherwise they are too hard to understand.
>
> - Avoiding actions firing other actions makes your app simple. We use the newest Dispatcher implementation from Facebook that does not allow a new dispatch while dispatching. It forces you to do things right.
>
> [Read the full article...](http://www.code-experience.com/async-requests-with-react-js-and-flux-revisited/)
## Undo-Redo with Immutable Data Structures
[Ameya Karve](https://github.com/ameyakarve) explained how to use [Mori](https://github.com/swannodette/mori), a library that provides immutable data structures, in order to [implement undo-redo](http://ameyakarve.com/jekyll/update/2014/02/06/Undo-React-Flux-Mori.html). This usually very challenging feature only takes a few lines of code with Flux!
```javascript
undo: function() {
this.redoStates = Mori.conj(this.redoStates, Mori.first(this.undoStates));
this.undoStates = Mori.drop(1, this.undoStates);
this.todosState = Mori.first(this.undoStates);
this.canUndo = Mori.count(this.undoStates) > 1;
this.canRedo = true;
if (Mori.count(this.undoStates) > 1) {
this.todos = JSON.parse(this.todosState);
} else {
this.todos = [];
}
this.emit('change');
},
```
## Flux in practice
[Gary Chambers](https://twitter.com/garychambers108) wrote a [guide to get started with Flux](https://medium.com/@garychambers108/flux-in-practice-ec08daa9041a). This is a very practical introduction to Flux.
> So, what does it actually mean to write an application in the Flux way? At that moment of inspiration, when faced with an empty text editor, how should you begin? This post follows the process of building a Flux-compliant application from scratch.
>
> [Read the full guide...](https://medium.com/@garychambers108/flux-in-practice-ec08daa9041a)
## Components, React and Flux
[Dan Abramov](https://twitter.com/dan_abramov) working at Stampsy made a talk about React and Flux. It's a very good overview of the concepts at play.
<iframe src="//slides.com/danabramov/components-react-flux-wip/embed" width="650" height="315" scrolling="no" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
## React and Flux
[Christian Alfoni](https://github.com/christianalfoni) wrote an article where [he compares Backbone, Angular and Flux](http://christianalfoni.github.io/javascript/2014/08/20/react-js-and-flux.html) on a simple example that's representative of a real project he worked on.
> Wow, that was a bit more code! Well, try to think of it like this. In the above examples, if we were to do any changes to the application we would probably have to move things around. In the FLUX example we have considered that from the start.
>
> Any changes to the application is adding, not moving things around. If you need a new store, just add it and make components dependant of it. If you need more views, create a component and use it inside any other component without affecting their current "parent controller or models".
>
> [Read the full article...](http://christianalfoni.github.io/javascript/2014/08/20/react-js-and-flux.html)
## Flux: Step by Step approach
[Nicola Paolucci](https://github.com/durdn) from Atlassian wrote a great guide to help your getting understand [Flux step by step](http://blogs.atlassian.com/2014/08/flux-architecture-step-by-step/).
<center>
<a href="http://blogs.atlassian.com/2014/08/flux-architecture-step-by-step/"><img src="/react/img/blog/flux-chart.png" width="400" /></a>
</center>
## DeLorean: Back to the future!
[DeLorean](https://github.com/deloreanjs/delorean) is a tiny Flux pattern implementation developed by [Fatih Kadir Akin](https://github.com/f).
>
- Unidirectional data flow, it makes your app logic simpler than MVC
- Automatically listens to data changes and keeps your data updated
- Makes data more consistent across your whole application
- It's framework agnostic, completely. There's no view framework dependency
- Very small, just 4K gzipped
- Built-in React.js integration, easy to use with Flight.js and Ractive.js and probably all others
- Improve your UI/data consistency using rollbacks
## Facebook's iOS Infrastructure
Last but not least, Flux and React ideas are not limited to JavaScript inside of the browser. The iOS team at Facebook re-implemented Newsfeed using very similar patterns.
<iframe width="650" height="315" src="//www.youtube.com/embed/XhXC4SKOGfQ" frameborder="0" allowfullscreen></iframe>
## Random Tweet
<blockquote class="twitter-tweet" lang="en"><p>If you build your app with flux, you can swap out React for a canvas or svg view layer and keep 85% of your code. (or the thing after React)</p>&mdash; Ryan Florence (@ryanflorence) <a href="https://twitter.com/ryanflorence/status/507309645372076034">September 3, 2014</a></blockquote>

15
_posts/2014-10-27-react-js-conf.md

@ -0,0 +1,15 @@
---
title: React.js Conf
author: Vjeux
---
Every few weeks someone asks us when we are going to organize a conference for React. Our answer has always been "some day". In the mean time, people have been talking about React at other JavaScript conferences around the world. But now the time has finally come for us to have a conference of our own.
**We're happy to announce [React.js Conf](http://conf.reactjs.com/)! It will take place January 28-29, 2015 on Facebook's campus in Menlo Park, California.**
Before we open registration, [we're looking for great talks](http://conf.reactjs.com/call-for-presenters.html). We want to see how you pushed application development forward! If you ever talked to a meet-up, pitched React to your co-workers, or done something awesome and want to talk about it, let us know!
Here are some areas of research we want to explore during the conference if you need some inspiration: server-side rendering, data fetching, language features (eg es6, clojure), immutability, rendering targets (eg svg, canvas), real-time updates...
We look forward to seeing many of you in person in just a few short months!

127
_posts/2014-10-28-react-v0.12.md

@ -0,0 +1,127 @@
---
title: React v0.12
author: Paul O’Shannessy
---
We're happy to announce the availability of React v0.12! After over a week of baking as the release candidate, we uncovered and fixed a few small issues. Thanks to all of you who upgraded and gave us feedback!
We have talked a lot about some of the bigger changes in this release. [We introduced new terminology](/react/blog/2014/10/14/introducing-react-elements.html) and changed APIs to clean up and simplify some of the concepts of React. [We also made several changes to JSX](/react/blog/2014/10/16/react-v0.12-rc1.html) and deprecated a few functions. We won't go into depth about these changes again but we encourage you to read up on these changes in the linked posts. We'll summarize these changes and discuss some of the other changes and how they may impact you below. As always, a full changelog is also included below.
The release is available for download:
* **React**
Dev build with warnings: <http://fb.me/react-0.12.0.js>
Minified build for production: <http://fb.me/react-0.12.0.min.js>
* **React with Add-Ons**
Dev build with warnings: <http://fb.me/react-with-addons-0.12.0.js>
Minified build for production: <http://fb.me/react-with-addons-0.12.0.min.js>
* **In-Browser JSX transformer**
<http://fb.me/JSXTransformer-0.12.0.js>
We've also published version `0.12.0` of the `react` and `react-tools` packages on npm and the `react` package on bower.
## New Terminology & Updated APIs
v0.12 is bringing about some new terminology. [We introduced](/react/blog/2014/10/14/introducing-react-elements.html) this 2 weeks ago and we've also documented it in [a new section of the documentation](/react/docs/glossary.html). As a part of this, we also corrected many of our top-level APIs to align with the terminology. `Component` has been removed from all of our `React.render*` methods. While at one point the argument you passed to these functions was called a Component, it no longer is. You are passing ReactElements. To align with `render` methods in your component classes, we decided to keep the top-level functions short and sweet. `React.renderComponent` is now `React.render`.
We also corrected some other misnomers. `React.isValidComponent` actually determines if the argument is a ReactElement, so it has been renamed to `React.isValidElement`. In the same vein, `React.PropTypes.component` is now `React.PropTypes.element` and `React.PropTypes.renderable` is now `React.PropTypes.node`.
The old methods will still work but will warn upon first use. They will be removed in v0.13.
## JSX Changes
[We talked more in depth about these before](/react/blog/2014/10/16/react-v0.12-rc1.html#jsx-changes), so here are the highlights.
* No more `/** @jsx React.DOM */`!
* We no longer transform to a straight function call. `<Component/>` now becomes `React.createElement(Component)`
* DOM components don't make use of `React.DOM`, instead we pass the tag name directly. `<div/>` becomes `React.createElement('div')`
* We introduced spread attributes as a quick way to transfer props.
## DevTools Improvements, No More `__internals`
For months we've gotten complaints about the React DevTools message. It shouldn't have logged the up-sell message when you were already using the DevTools. Unfortunately this was because the way we implemented these tools resulted in the DevTools knowing about React, but not the reverse. We finally gave this some attention and enabled React to know if the DevTools are installed. We released an update to the devtools several weeks ago making this possible. Extensions in Chrome should auto-update so you probably already have the update installed!
As a result of this update, we no longer need to expose several internal modules to the world. If you were taking advantage of this implementation detail, your code will break. `React.__internals` is no more.
## License Change - BSD
We updated the license on React to the BSD 3-Clause license with an explicit patent grant. Previously we used the Apache 2 license. These licenses are very similar and our extra patent grant is equivalent to the grant provided in the Apache license. You can still use React with the confidence that we have granted the use of any patents covering it. This brings us in line with the same licensing we use across the majority of our open source projects at Facebook.
You can read the full text of the [LICENSE](https://github.com/facebook/react/blob/master/LICENSE) and [`PATENTS`](https://github.com/facebook/react/blob/master/PATENTS) files on GitHub.
- - -
## Changelog
### React Core
#### Breaking Changes
* `key` and `ref` moved off props object, now accessible on the element directly
* React is now BSD licensed with accompanying Patents grant
* Default prop resolution has moved to Element creation time instead of mount time, making them effectively static
* `React.__internals` is removed - it was exposed for DevTools which no longer needs access
* Composite Component functions can no longer be called directly - they must be wrapped with `React.createFactory` first. This is handled for you when using JSX.
#### New Features
* Spread operator (`{...}`) introduced to deprecate `this.transferPropsTo`
* Added support for more HTML attributes: `acceptCharset`, `classID`, `manifest`
#### Deprecations
* `React.renderComponent` --> `React.render`
* `React.renderComponentToString` --> `React.renderToString`
* `React.renderComponentToStaticMarkup` --> `React.renderToStaticMarkup`
* `React.isValidComponent` --> `React.isValidElement`
* `React.PropTypes.component` --> `React.PropTypes.element`
* `React.PropTypes.renderable` --> `React.PropTypes.node`
* **DEPRECATED** `React.isValidClass`
* **DEPRECATED** `instance.transferPropsTo`
* **DEPRECATED** Returning `false` from event handlers to preventDefault
* **DEPRECATED** Convenience Constructor usage as function, instead wrap with `React.createFactory`
* **DEPRECATED** use of `key={null}` to assign implicit keys
#### Bug Fixes
* Better handling of events and updates in nested results, fixing value restoration in "layered" controlled components
* Correctly treat `event.getModifierState` as case sensitive
* Improved normalization of `event.charCode`
* Better error stacks when involving autobound methods
* Removed DevTools message when the DevTools are installed
* Correctly detect required language features across browsers
* Fixed support for some HTML attributes:
* `list` updates correctly now
* `scrollLeft`, `scrollTop` removed, these should not be specified as props
* Improved error messages
### React With Addons
#### New Features
* `React.addons.batchedUpdates` added to API for hooking into update cycle
#### Breaking Changes
* `React.addons.update` uses `assign` instead of `copyProperties` which does `hasOwnProperty` checks. Properties on prototypes will no longer be updated correctly.
#### Bug Fixes
* Fixed some issues with CSS Transitions
### JSX
#### Breaking Changes
* Enforced convention: lower case tag names are always treated as HTML tags, upper case tag names are always treated as composite components
* JSX no longer transforms to simple function calls
#### New Features
* `@jsx React.DOM` no longer required
* spread (`{...}`) operator introduced to allow easier use of props
#### Bug Fixes
* JSXTransformer: Make sourcemaps an option when using APIs directly (eg, for react-rails)

48
docs/02-displaying-data.md

@ -35,8 +35,6 @@ Let's look at a really simple example. Create a `hello-react.html` file with the
For the rest of the documentation, we'll just focus on the JavaScript code and assume it's inserted into a template like the one above. Replace the placeholder comment above with the following JS:
```javascript
/** @jsx React.DOM */
var HelloWorld = React.createClass({
render: function() {
return (
@ -49,7 +47,7 @@ var HelloWorld = React.createClass({
});
setInterval(function() {
React.renderComponent(
React.render(
<HelloWorld date={new Date()} />,
document.getElementById('example')
);
@ -79,12 +77,50 @@ React components are very simple. You can think of them as simple function that
We strongly believe that components are the right way to separate concerns rather than "templates" and "display logic." We think that markup and the code that generates it are intimately tied together. Additionally, display logic is often very complex and using template languages to express it becomes cumbersome.
We've found that the best solution for this problem is to generate markup directly from the JavaScript code such that you can use all of the expressive power of a real programming language to build UIs. In order to make this easier, we've added a very simple, **optional** HTML-like syntax for the function calls that generate markup called JSX.
We've found that the best solution for this problem is to generate HTML and component trees directly from the JavaScript code such that you can use all of the expressive power of a real programming language to build UIs.
In order to make this easier, we've added a very simple, **optional** HTML-like syntax to create these React tree nodes.
**JSX lets you create JavaScript objects using HTML syntax.** To generate a link in React using pure JavaScript you'd write:
`React.createElement('a', {href: 'http://facebook.github.io/react/'}, 'Hello!')`
With JSX this becomes:
**JSX lets you write JavaScript function calls with HTML syntax.** To generate a link in React using pure JavaScript you'd write: `React.DOM.a({href: 'http://facebook.github.io/react/'}, 'Hello React!')`. With JSX this becomes `<a href="http://facebook.github.io/react/">Hello React!</a>`. We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.**
`<a href="http://facebook.github.io/react/">Hello!</a>`
JSX is very small; the "hello, world" example above uses every feature of JSX. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.**
JSX is very small. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
The easiest way to get started with JSX is to use the in-browser `JSXTransformer`. We strongly recommend that you don't use this in production. You can precompile your code using our command-line [react-tools](http://npmjs.org/package/react-tools) package.
## React without JSX
JSX is completely optional. You don't have to use JSX with React. You can create these trees through `React.createElement`. The first argument is the tag, pass a properties object as the second argument and children to the third argument.
```javascript
var child = React.createElement('li', null, 'Text Content');
var root = React.createElement('ul', { className: 'my-list' }, child);
React.render(root, document.body);
```
As a convenience you can create short-hand factory function to create elements from custom components.
```javascript
var Factory = React.createFactory(ComponentClass);
...
var root = Factory({ custom: 'prop' });
React.render(root, document.body);
```
React already have built-in factories for common HTML tags:
```javascript
var root = React.DOM.ul({ className: 'my-list' },
React.DOM.li(null, 'Text Content')
);
```

8
docs/02-displaying-data.zh-CN.md

@ -35,8 +35,6 @@ next: jsx-in-depth.html
在接下去的文档中,我们只关注 JavaScript 代码,假设我们把代码插入到上面那个模板中。用下面的代码替换掉上面用来占位的注释。
```javascript
/** @jsx React.DOM */
var HelloWorld = React.createClass({
render: function() {
return (
@ -49,7 +47,7 @@ var HelloWorld = React.createClass({
});
setInterval(function() {
React.renderComponent(
React.render(
<HelloWorld date={new Date()} />,
document.getElementById('example')
);
@ -78,10 +76,10 @@ React 组件非常简单。你可以认为它们就是简单的函数,接受 `
我们得出解决这个问题最好的方案是通过 JavaScript 直接生成模板,这样你就可以用一个真正语言的所有表达能力去构建用户界面。为了使这变得更简单,我们做了一个非常简单、**可选**类似 HTML 语法 ,通过函数调用即可生成模板的编译器,称为 JSX。
**JSX 让你可以用 HTML 语法去写 JavaScript 函数调用** 为了在 React 生成一个链接,通过纯 JavaScript 你可以这么写: `React.DOM.a({href: 'http://facebook.github.io/react/'}, 'Hello React!')`。通过 JSX 这就变成了 `<a href="http://facebook.github.io/react/">Hello React!</a>`。我们发现这会使搭建 React 应用更加简单,设计师也偏向用这用语法,但是每个人可以有它们自己的工作流,所以**JSX 不是必须用的。**
**JSX 让你可以用 HTML 语法去写 JavaScript 函数调用** 为了在 React 生成一个链接,通过纯 JavaScript 你可以这么写: `React.createElement('a', {href: 'http://facebook.github.io/react/'}, 'Hello React!')`。通过 JSX 这就变成了 `<a href="http://facebook.github.io/react/">Hello React!</a>`。我们发现这会使搭建 React 应用更加简单,设计师也偏向用这用语法,但是每个人可以有它们自己的工作流,所以**JSX 不是必须用的。**
JSX 非常小;上面“hello, world”的例子使用了 JSX 所有的特性。想要了解更多,请看 [深入理解 JSX](/react/docs/jsx-in-depth.html)。或者直接使用[在线 JSX 编译器](/react/jsx-compiler.html)观察变化过程。
JSX 类似于 HTML,但不是完全一样。参考[JSX gotchas](/react/docs/jsx-gotchas.html) 学习关键区别。
最简单开始学习 JSX 的方法就是使用浏览器端的 `JSXTransformer`。我们强烈建议你不要在生产环境中使用它。你可以通过我们的命令行工具 [react-tools](http://npmjs.org/package/react-tools) 包来预编译你的代码。
最简单开始学习 JSX 的方法就是使用浏览器端的 `JSXTransformer`。我们强烈建议你不要在生产环境中使用它。你可以通过我们的命令行工具 [react-tools](http://npmjs.org/package/react-tools) 包来预编译你的代码。

158
docs/02.1-jsx-in-depth.md

@ -3,45 +3,58 @@ id: jsx-in-depth
title: JSX in Depth
permalink: jsx-in-depth.html
prev: displaying-data.html
next: jsx-gotchas.html
next: jsx-spread.html
---
JSX is a JavaScript XML syntax transform recommended for use
with React.
> Note:
>
> Don't forget the `/** @jsx React.DOM */` pragma at the beginning of your file! This tells JSX to process the file for React.
>
> If you don't include the pragma, your source will remain untouched, so it's safe to run the JSX transformer on all JS files in your codebase if you want to.
[JSX](http://facebook.github.io/jsx/) is a JavaScript syntax extension that looks similar to XML. You can use a simple JSX syntactic transform with React.
## Why JSX?
React works out of the box without JSX. Simply construct your markup using the
functions on `React.DOM`. For example, here's how to construct a simple link:
You don't have to use JSX with React. You can just use plain JS. However, we recommend using JSX because it is a concise and familiar syntax for defining tree structures with attributes.
It's more familiar for casual developers such as designers.
XML has the benefit of balanced open and closing tags. This helps make large trees easier to read than function calls or object literals.
It doesn't alter the semantics of JavaScript.
## HTML Tags vs. React Components
React can either render HTML tags (strings) or React components (classes).
To render a HTML tag, just use lower-case tag names in JSX:
```javascript
var link = React.DOM.a({href: 'http://facebook.github.io/react'}, 'React');
var myDivElement = <div className="foo" />;
React.render(myDivElement, document.body);
```
We recommend using JSX for many reasons:
To render a React Component, just a local variable that starts with an upper-case letter:
* It's easier to visualize the structure of the DOM.
* Designers are more comfortable making changes.
* It's familiar for those who have used MXML or XAML.
```javascript
var MyComponent = React.createClass({/*...*/});
var myElement = <MyComponent someProperty={true} />;
React.render(myElement, document.body);
```
React's JSX uses the upper vs. lower case convention to distinguish between local component classes and HTML tags.
> Note:
>
> Since JSX is JavaScript, identifiers such as `class` and `for` are discouraged
> as XML attribute names. Instead, React DOM components expect DOM property
> names like `className` and `htmlFor`, respectively.
## The Transform
JSX transforms from an XML-like syntax into native JavaScript. XML elements and
attributes are transformed into function calls and objects, respectively.
React JSX transforms from an XML-like syntax into native JavaScript. XML elements, attributes and children are transformed into arguments to `React.createElement`.
```javascript
var Nav;
// Input (JSX):
var app = <Nav color="blue" />;
// Output (JS):
var app = Nav({color:"blue"});
var app = React.createElement(Nav, {color:"blue"});
```
Notice that in order to use `<Nav />`, the `Nav` variable must be in scope.
@ -53,85 +66,26 @@ var Nav, Profile;
// Input (JSX):
var app = <Nav color="blue"><Profile>click</Profile></Nav>;
// Output (JS):
var app = Nav({color:"blue"}, Profile(null, "click"));
var app = React.createElement(
Nav,
{color:"blue"},
React.createElement(Profile, null, "click")
);
```
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
desugars into native JavaScript, and the
desugars into native JavaScript, and the
[HTML to JSX converter](/react/html-jsx.html) to convert your existing HTML to
JSX.
If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows
how to setup compilation.
> Note:
>
> Details about the code transform are given here to increase understanding, but
> your code should not rely on these implementation details.
## React and JSX
React and JSX are independent technologies, but JSX was primarily built with
React in mind. The two valid uses of JSX are:
* To construct instances of React DOM components (`React.DOM.*`).
* To construct instances of composite components created with
`React.createClass()`.
### React DOM Components
To construct a `<div>` is to create a variable that refers to `React.DOM.div`.
```javascript
var div = React.DOM.div;
var app = <div className="appClass">Hello, React!</div>;
```
### React Composite Components
To construct an instance of a composite component, create a variable that
references the class.
```javascript
var MyComponent = React.createClass({/*...*/});
var app = <MyComponent someProperty={true} />;
```
JSX will infer the component's name from the variable assignment and specify
the class's [displayName](/react/docs/component-specs.html#displayName) accordingly.
See [Multiple Components](/react/docs/multiple-components.html) to learn more about using composite components.
If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows how to setup compilation.
> Note:
>
> Since JSX is JavaScript, identifiers such as `class` and `for` are discouraged
> as XML attribute names. Instead, React DOM components expect attributes like
> `className` and `htmlFor`, respectively.
## DOM Convenience
Having to define variables for every type of DOM element can get tedious
(e.g. `var div, span, h1, h2, ...`). JSX provides a convenience to address this
problem by allowing you to specify a variable in an `@jsx` docblock field. JSX
will use that field to find DOM components.
```javascript
/**
* @jsx React.DOM
*/
var Nav;
// Input (JSX):
var tree = <Nav><span /></Nav>;
// Output (JS):
var tree = Nav(null, React.DOM.span(null));
```
> Remember:
>
> JSX simply transforms elements into function calls and has no notion of the
> DOM. The docblock parameter is only a convenience to resolve the most commonly
> used elements. In general, JSX has no notion of the DOM.
> The JSX expression always evaluates to a ReactElement. The actual
> implementation details may vary. An optimized mode could inline the
> ReactElement as an object literal to bypass the validation code in
> `React.createElement`.
## Namespaced Components
@ -206,7 +160,10 @@ pair of curly braces (`{}`) instead of quotes (`""`).
// Input (JSX):
var person = <Person name={window.isLoggedIn ? window.name : ''} />;
// Output (JS):
var person = Person({name: window.isLoggedIn ? window.name : ''});
var person = React.createElement(
Person,
{name: window.isLoggedIn ? window.name : ''}
);
```
### Child Expressions
@ -217,7 +174,11 @@ Likewise, JavaScript expressions may be used to express children:
// Input (JSX):
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
// Output (JS):
var content = Container(null, window.isLoggedIn ? Nav(null) : Login(null));
var content = React.createElement(
Container,
null,
window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
);
```
### Comments
@ -238,14 +199,7 @@ var content = (
);
```
## Prior Work
JSX is similar to several other JavaScript embedded XML language
proposals/projects. Some of the features of JSX that distinguish it from similar
efforts include:
* JSX is a simple syntactic transform.
* JSX neither provides nor requires a runtime library.
* JSX does not alter or add to the semantics of JavaScript.
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
> NOTE:
>
> JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
>>>>>>> master

71
docs/02.2-jsx-spread.md

@ -0,0 +1,71 @@
---
id: jsx-spread
title: JSX Spread Attributes
permalink: jsx-spread.html
prev: jsx-in-depth.html
next: jsx-gotchas.html
---
If you know all the properties that you want to place on a component ahead of time, it is easy to use JSX:
```javascript
var component = <Component foo={x} bar={y} />;
```
## Mutating Props is Bad, mkay
If you don't know which properties you want to set, you might be tempted to add them onto the object later:
```javascript
var component = <Component />;
component.props.foo = x; // bad
component.props.bar = y; // also bad
```
This is an anti-pattern because it means that we can't help you check the right propTypes until way later. This means that your propTypes errors end up with a cryptic stack trace.
The props should be considered immutable at this point. Mutating the props object somewhere else could cause unexpected consequences so ideally it would be a frozen object at this point.
## Spread Attributes
Now you can use a new feature of JSX called spread attributes:
```javascript
var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;
```
The properties of the object that you pass in are copied onto the component's props.
You can use this multiple times or combine it with other attributes. The specification order is important. Later attributes override previous ones.
```javascript
var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'
```
## What's with the weird `...` notation?
The `...` operator (or spread operator) is already supported for [arrays in ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). There is also an ES7 proposal for [Object Rest and Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread).
In fact, you can already use this in our code base as an experimental syntax:
```javascript
var oldObj = { foo: 'hello', bar: 'world' };
var newObj = { ...oldObj, foo: 'hi' };
console.log(newObj.foo); // 'hi';
console.log(newObj.bar); // 'world';
```
Merging two objects can be expressed as:
```javascript
var ab = { ...a, ...b };
```
> Note:
>
> Use the [JSX command-line tool](http://npmjs.org/package/react-tools) with the `--harmony` flag to activate the experimental ES7 syntax.

2
docs/02.2-jsx-gotchas.md → docs/02.3-jsx-gotchas.md

@ -2,7 +2,7 @@
id: jsx-gotchas
title: JSX Gotchas
permalink: jsx-gotchas.html
prev: jsx-in-depth.html
prev: jsx-spread.html
next: interactivity-and-dynamic-uis.html
---

8
docs/03-interactivity-and-dynamic-uis.md

@ -12,8 +12,6 @@ You've already [learned how to display data](/react/docs/displaying-data.html) w
## A Simple Example
```javascript
/** @jsx React.DOM */
var LikeButton = React.createClass({
getInitialState: function() {
return {liked: false};
@ -31,7 +29,7 @@ var LikeButton = React.createClass({
}
});
React.renderComponent(
React.render(
<LikeButton />,
document.getElementById('example')
);
@ -47,9 +45,9 @@ If you'd like to use React on a touch device such as a phone or tablet, simply c
## Under the Hood: Autobinding and Event Delegation
Under the hood React does a few things to keep your code performant and easy to understand.
Under the hood, React does a few things to keep your code performant and easy to understand.
**Autobinding:** When creating callbacks in JavaScript you usually need to explicitly bind a method to its instance such that the value of `this` is correct. With React, every method is automatically bound to its component instance. React caches the bound method such that it's extremely CPU and memory efficient. It's also less typing!
**Autobinding:** When creating callbacks in JavaScript, you usually need to explicitly bind a method to its instance such that the value of `this` is correct. With React, every method is automatically bound to its component instance. React caches the bound method such that it's extremely CPU and memory efficient. It's also less typing!
**Event delegation:** React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops. To learn more about why this is fast, see [David Walsh's excellent blog post](http://davidwalsh.name/event-delegate).

8
docs/04-multiple-components.md

@ -19,8 +19,6 @@ By building modular components that reuse other components with well-defined int
Let's create a simple Avatar component which shows a profile picture and username using the Facebook Graph API.
```javascript
/** @jsx React.DOM */
var Avatar = React.createClass({
render: function() {
return (
@ -50,7 +48,7 @@ var ProfileLink = React.createClass({
}
});
React.renderComponent(
React.render(
<Avatar username="pwh" />,
document.getElementById('example')
);
@ -178,14 +176,14 @@ You can also key children by passing an object. The object keys will be used as
```javascript
render: function() {
var items = {};
this.props.results.forEach(function(result) {
// If result.id can look like a number (consider short hashes), then
// object iteration order is not guaranteed. In this case, we add a prefix
// to ensure the keys are strings.
items['result-' + result.id] = <li>{result.text}</li>;
});
return (
<ol>
{items}

31
docs/05-reusable-components.md

@ -3,7 +3,7 @@ id: reusable-components
title: Reusable Components
permalink: reusable-components.html
prev: multiple-components.html
next: forms.html
next: transferring-props.html
---
When designing interfaces, break down the common design elements (buttons, form fields, layout components, etc) into reusable components with well-defined interfaces. That way, the next time you need to build some UI you can write much less code, which means faster development time, fewer bugs, and fewer bytes down the wire.
@ -25,12 +25,12 @@ React.createClass({
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
// Anything that can be rendered: numbers, strings, components or an array
// Anything that can be rendered: numbers, strings, elements or an array
// containing these types.
optionalRenderable: React.PropTypes.renderable,
optionalNode: React.PropTypes.node,
// A React component.
optionalComponent: React.PropTypes.component,
// A React element.
optionalElement: React.PropTypes.element,
// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
@ -100,21 +100,18 @@ The result of `getDefaultProps()` will be cached and used to ensure that `this.p
## Transferring Props: A Shortcut
A common type of React component is one that extends a basic HTML in a simple way. Often you'll want to copy any HTML attributes passed to your component to the underlying HTML element to save typing. React provides `transferPropsTo()` to do just this.
A common type of React component is one that extends a basic HTML in a simple way. Often you'll want to copy any HTML attributes passed to your component to the underlying HTML element to save typing. You can use the JSX _spread_ syntax to achieve this:
```javascript
/** @jsx React.DOM */
var CheckLink = React.createClass({
render: function() {
// transferPropsTo() will take any props passed to CheckLink
// and copy them to <a>
return this.transferPropsTo(<a>{'√ '}{this.props.children}</a>);
// This takes any props passed to CheckLink and copies them to <a>
return <a {...this.props}>{'√ '}{this.props.children}</a>;
}
});
React.renderComponent(
<CheckLink href="javascript:alert('Hello, world!');">
React.render(
<CheckLink href="/checked.html">
Click here!
</CheckLink>,
document.getElementById('example')
@ -123,13 +120,13 @@ React.renderComponent(
## Single Child
With `React.PropTypes.component` you can specify that only a single child can be passed to
With `React.PropTypes.element` you can specify that only a single child can be passed to
a component as children.
```javascript
var MyComponent = React.createClass({
propTypes: {
children: React.PropTypes.component.isRequired
children: React.PropTypes.element.isRequired
},
render: function() {
@ -150,8 +147,6 @@ Components are the best way to reuse code in React, but sometimes very different
One common use case is a component wanting to update itself on a time interval. It's easy to use `setInterval()`, but it's important to cancel your interval when you don't need it anymore to save memory. React provides [lifecycle methods](/react/docs/working-with-the-browser.html#component-lifecycle) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed.
```javascript
/** @jsx React.DOM */
var SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
@ -184,7 +179,7 @@ var TickTock = React.createClass({
}
});
React.renderComponent(
React.render(
<TickTock />,
document.getElementById('example')
);

159
docs/06-transferring-props.md

@ -0,0 +1,159 @@
---
id: transferring-props
title: Transferring Props
permalink: transferring-props.html
prev: reusable-components.html
next: forms.html
---
It's a common pattern in React to wrap a component in an abstraction. The outer component exposes a simple property to do something that might have more complex implementation details.
You can use [JSX spread attributes](/react/docs/jsx-spread.html) to merge the old props with additional values:
```javascript
return <Component {...this.props} more="values" />;
```
If you don't use JSX, you can use any object helper such as ES6 `Object.assign` or Underscore `_.extend`:
```javascript
return Component(Object.assign({}, this.props, { more: 'values' }));
```
The rest of this tutorial explains best practices. It uses JSX and experimental ES7 syntax.
## Manual Transfer
Most of the time you should explicitly pass the properties down. That ensures that you only exposes a subset of the inner API, one that you know will work.
```javascript
var FancyCheckbox = React.createClass({
render: function() {
var fancyClass = this.props.checked ? 'FancyChecked' : 'FancyUnchecked';
return (
<div className={fancyClass} onClick={this.props.onClick}>
{this.props.children}
</div>
);
}
});
React.render(
<FancyCheckbox checked={true} onClick={console.log}>
Hello world!
</FancyCheckbox>,
document.body
);
```
But what about the `name` prop? Or the `title` prop? Or `onMouseOver`?
## Transferring with `...` in JSX
Sometimes it's fragile and tedious to pass every property along. In that case you can use [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) with rest properties to extract a set of unknown properties.
List out all the properties that you would like to consume, followed by `...other`.
```javascript
var { checked, ...other } = this.props;
```
This ensures that you pass down all the props EXCEPT the ones you're consuming yourself.
```javascript
var FancyCheckbox = React.createClass({
render: function() {
var { checked, ...other } = this.props;
var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
// `other` contains { onClick: console.log } but not the checked property
return (
<div {...other} className={fancyClass} />
);
}
});
React.render(
<FancyCheckbox checked={true} onClick={console.log}>
Hello world!
</FancyCheckbox>,
document.body
);
```
> NOTE:
>
> In the example above, the `checked` prop is also a valid DOM attribute. If you didn't use destructuring in this way you might inadvertently pass it along.
Always use the destructuring pattern when transferring unknown `other` props.
```javascript
var FancyCheckbox = React.createClass({
render: function() {
var fancyClass = this.props.checked ? 'FancyChecked' : 'FancyUnchecked';
// ANTI-PATTERN: `checked` would be passed down to the inner component
return (
<div {...this.props} className={fancyClass} />
);
}
});
```
## Consuming and Transferring the Same Prop
If your component wants to consume a property but also pass it along, you can repass it explicitly `checked={checked}`. This is preferable to passing the full `this.props` object since it's easier to refactor and lint.
```javascript
var FancyCheckbox = React.createClass({
render: function() {
var { checked, title, ...other } = this.props;
var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
var fancyTitle = checked ? 'X ' + title : 'O ' + title;
return (
<label>
<input {...other}
checked={checked}
className={fancyClass}
type="checkbox"
/>
{fancyTitle}
</label>
);
}
});
```
> NOTE:
>
> Order matters. By putting the `{...other}` before your JSX props you ensure that the consumer of your component can't override them. In the example above we have guaranteed that the input will be of type `"checkbox"`.
## Rest and Spread Properties `...`
Rest properties allow you to extract the remaining properties from an object into a new object. It excludes every other property listed in the destructuring pattern.
This is an experimental implementation of an [ES7 proposal](https://github.com/sebmarkbage/ecmascript-rest-spread).
```javascript
var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
z; // { a: 3, b: 4 }
```
> Note:
>
> Use the [JSX command-line tool](http://npmjs.org/package/react-tools) with the `--harmony` flag to activate the experimental ES7 syntax.
## Transferring with Underscore
If you don't use JSX, you can use a library to achieve the same pattern. Underscore supports `_.omit` to filter out properties and `_.extend` to copy properties onto a new object.
```javascript
var FancyCheckbox = React.createClass({
render: function() {
var checked = this.props.checked;
var other = _.omit(this.props, 'checked');
var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
return (
React.DOM.div(_.extend({}, other, { className: fancyClass }))
);
}
});
```

2
docs/06-forms.md → docs/07-forms.md

@ -2,7 +2,7 @@
id: forms
title: Forms
permalink: forms.html
prev: reusable-components.html
prev: transferring-props.html
next: working-with-the-browser.html
---

4
docs/07-working-with-the-browser.md → docs/08-working-with-the-browser.md

@ -29,8 +29,6 @@ To interact with the browser, you'll need a reference to a DOM node. Every mount
In order to get a reference to a React component, you can either use `this` to get the current React component, or you can use refs to refer to a component you own. They work like this:
```javascript
/** @jsx React.DOM */
var MyComponent = React.createClass({
handleClick: function() {
// Explicitly focus the text input using the raw DOM API.
@ -52,7 +50,7 @@ var MyComponent = React.createClass({
}
});
React.renderComponent(
React.render(
<MyComponent />,
document.getElementById('example')
);

0
docs/07.1-more-about-refs.md → docs/08.1-more-about-refs.md

2
docs/08-tooling-integration.md → docs/09-tooling-integration.md

@ -23,7 +23,7 @@ We have instructions for building from `master` [in our GitHub repository](https
### In-browser JSX Transform
If you like using JSX, we provide an in-browser JSX transformer for development [on our download page](/react/downloads.html). Simply include a `<script type="text/jsx">` tag to engage the JSX transformer. Be sure to include the `/** @jsx React.DOM */` comment as well, otherwise the transformer will not run the transforms.
If you like using JSX, we provide an in-browser JSX transformer for development [on our download page](/react/downloads.html). Simply include a `<script type="text/jsx">` tag to engage the JSX transformer.
> Note:
>

0
docs/09-addons.md → docs/10-addons.md

33
docs/09.1-animation.md → docs/10.1-animation.md

@ -16,9 +16,7 @@ React provides a `ReactTransitionGroup` addon component as a low-level API for a
`ReactCSSTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out.
```javascript{30-32}
/** @jsx React.DOM */
```javascript{28-30}
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var TodoList = React.createClass({
@ -54,6 +52,9 @@ var TodoList = React.createClass({
}
});
```
> Note:
>
> You must provide [the `key` attribute](/react/docs/multiple-components.html#dynamic-children) for all children of `ReactCSSTransitionGroup`, even if rendering a single item. This is how React will determine which children have entered, left, or stayed.
In this component, when a new item is added to `ReactCSSTransitionGroup` 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.
@ -87,7 +88,7 @@ You'll notice that when you try to remove an item `ReactCSSTransitionGroup` keep
In order for it to apply transitions to its children, the `ReactCSSTransitionGroup` must already be mounted in the DOM. The example below would not work, because the `ReactCSSTransitionGroup` is being mounted along with the new item, instead of the new item being mounted within it. Compare this to the [Getting Started](#getting-started) section above to see the difference.
```javascript{12-14}
```javascript{12-15}
render: function() {
var items = this.state.items.map(function(item, i) {
return (
@ -111,9 +112,7 @@ In order for it to apply transitions to its children, the `ReactCSSTransitionGro
Although in the example above we rendered a list of items into `ReactCSSTransitionGroup`, the children of `ReactCSSTransitionGroup` can be one or zero items. This makes it possible to animate a single element entering or leaving. Similarly, you can animate a new element replacing the current element, with the new element animating in while the current animates out. For example, we can implement a simple image carousel like this:
```javascript{12-14}
/** @jsx React.DOM */
```javascript{10-12}
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var ImageCarousel = React.createClass({
@ -132,10 +131,6 @@ var ImageCarousel = React.createClass({
});
```
> Note:
>
> You must provide [the `key` attribute](/react/docs/multiple-components.html#dynamic-children) for all children of `ReactCSSTransitionGroup`, even if rendering a single item. This is how React will determine which children have entered, left, or stayed.
### 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 `ReactCSSTransitionGroup` waits for an animation to complete before removing your DOM node. You can add `transitionEnter={false}` or `transitionLeave={false}` props to `ReactCSSTransitionGroup` to disable these animations.
@ -169,9 +164,21 @@ This is called when the `willLeave` `callback` is called (at the same time as `c
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{1}
<ReactTransitionGroup component={React.DOM.ul}>
<ReactTransitionGroup component="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!
Every DOM component that React can render is available for use. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself!
> Note:
>
> Prior to v0.12, when using DOM components, the `component` prop needed to be a reference to `React.DOM.*`. Since the component is simply passed to `React.createElement`, it must now be a string. Composite components must pass the factory.
Any additional, user-defined, properties will be become properties of the rendered component. For example, here's how you would you render a `<ul>` with css class:
```javascript{1}
<ReactTransitionGroup component="ul" className="animated-list">
...
</ReactTransitionGroup>
```

14
docs/09.2-form-input-binding-sugar.md → docs/10.2-form-input-binding-sugar.md

@ -6,7 +6,7 @@ prev: animation.html
next: class-name-manipulation.html
---
`ReactLink` is an easy way to express two-way binding with React.
`ReactLink` is an easy way to express two-way binding with React.
> Note:
>
@ -29,8 +29,6 @@ Two-way binding -- implicitly enforcing that some value in the DOM is always con
Here's a simple form example without using `ReactLink`:
```javascript
/** @jsx React.DOM */
var NoLink = React.createClass({
getInitialState: function() {
return {message: 'Hello!'};
@ -47,9 +45,7 @@ var NoLink = React.createClass({
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 */
```javascript{2,7}
var WithLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
@ -77,9 +73,7 @@ There are two sides to `ReactLink`: the place where you create the `ReactLink` i
### ReactLink Without LinkedStateMixin
```javascript{7-9,11-14}
/** @jsx React.DOM */
```javascript{5-7,9-12}
var WithoutMixin = React.createClass({
getInitialState: function() {
return {message: 'Hello!'};
@ -102,8 +96,6 @@ As you can see, `ReactLink` objects are very simple objects that just have a `va
### ReactLink Without valueLink
```javascript
/** @jsx React.DOM */
var WithoutLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {

0
docs/09.3-class-name-manipulation.md → docs/10.3-class-name-manipulation.md

6
docs/09.4-test-utils.md → docs/10.4-test-utils.md

@ -43,13 +43,13 @@ object mockComponent(function componentClass, string? mockTagName)
Pass a mocked component module to this method to augment it with useful methods that allow it to be used as a dummy React component. Instead of rendering as usual, the component will become a simple `<div>` (or other tag if `mockTagName` is provided) containing any provided children.
### isDescriptorOfType
### isElementOfType
```javascript
boolean isDescriptorOfType(ReactDescriptor descriptor, function componentClass)
boolean isElementOfType(ReactElement element, function componentClass)
```
Returns true if `descriptor` is an instance of a React `componentClass`.
Returns true if `element` is a ReactElement whose type is of a React `componentClass`.
### isDOMComponent

8
docs/09.5-clone-with-props.md → docs/10.5-clone-with-props.md

@ -10,12 +10,12 @@ In rare situations a component may want to change the props of a component that
#### `ReactComponent React.addons.cloneWithProps(ReactComponent component, object? extraProps)`
Do a shallow copy of `component` and merge any props provided by `extraProps`. Props are merged in the same manner as [`transferPropsTo()`](/react/docs/component-api.html#transferpropsto), so props like `className` will be merged intelligently.
Do a shallow copy of `component` and merge any props provided by `extraProps`. The `className` and `style` props will be merged intelligently.
> Note:
>
> `cloneWithProps` does not transfer the `key` prop to the cloned component. If you wish to preserve the key, add it to the `extraProps` object:
> `cloneWithProps` does not transfer `key` to the cloned component. If you wish to preserve the key, add it to the `extraProps` object:
> ```js
> var clonedComponent = cloneWithProps(originalComponent, { key : originalComponent.props.key });
> var clonedComponent = cloneWithProps(originalComponent, { key : originalComponent.key });
> ```
> `ref` is another prop that is not preserved either.
> `ref` is similarly not preserved.

0
docs/09.6-update.md → docs/10.6-update.md

0
docs/09.7-pure-render-mixin.md → docs/10.7-pure-render-mixin.md

0
docs/09.8-perf.md → docs/10.8-perf.md

18
docs/getting-started.md

@ -34,8 +34,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
<body>
<div id="example"></div>
<script type="text/jsx">
/** @jsx React.DOM */
React.renderComponent(
React.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
@ -51,18 +50,12 @@ The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](/r
Your React JSX code can live in a separate file. Create the following `src/helloworld.js`.
```javascript
/** @jsx React.DOM */
React.renderComponent(
React.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
```
> Note:
>
> ```/** @jsx React.DOM */``` is *required*. The comment parser is very strict right now; in order for it to pick up the `@jsx` modifier, two conditions are required. The `@jsx` comment block must be the first comment on the file. The comment must start with `/**` (`/*` and `//` will not work). If the parser can't find the `@jsx` comment, it will output the file without transforming it.
Then reference it from `helloworld.html`:
```html{10}
@ -86,10 +79,9 @@ jsx --watch src/ build/
The file `build/helloworld.js` is autogenerated whenever you make a change.
```javascript{3}
/** @jsx React.DOM */
React.renderComponent(
React.DOM.h1(null, 'Hello, world!'),
```javascript{2}
React.render(
React.createElement('h1', null, 'Hello, world!'),
document.getElementById('example')
);
```

19
docs/getting-started.zh-CN.md

@ -33,8 +33,7 @@ next: tutorial.html
<body>
<div id="example"></div>
<script type="text/jsx">
/** @jsx React.DOM */
React.renderComponent(
React.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
@ -50,15 +49,14 @@ next: tutorial.html
你的 React JSX 代码文件可以写在另外的文件里。新建下面的 `src/helloworld.js`
```javascript
/** @jsx React.DOM */
React.renderComponent(
React.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
```
然后在 `helloworld.html` 引用该文件:
```html{10}
<script type="text/jsx" src="src/helloworld.js"></script>
```
@ -80,18 +78,13 @@ jsx --watch src/ build/
只要你修改了, `build/helloworld.js` 文件会自动生成。
```javascript{3}
/** @jsx React.DOM */
React.renderComponent(
React.DOM.h1(null, 'Hello, world!'),
```javascript{2}
React.render(
React.createElement('h1', null, 'Hello, world!'),
document.getElementById('example')
);
```
> 注意:
>
> 目前注释解析器还是非常严格;为了让它能够找出 `@jsx` 修饰符,有两个限制是必须的。`@jsx` 注释块必须是代码文件第一个注释。注释必须以 `/**` (`/*` 和 `//` 不起作用) 开头。如果解析器找不到 `@jsx` 注释,它就不会转换代码,直接原样输出到文件。
对照下面更新你的 HTML 代码
```html{6,10}

42
docs/ref-01-top-level-api.md

@ -22,25 +22,25 @@ Create a component given a specification. A component implements a `render` meth
For more information about the specification object, see [Component Specs and Lifecycle](/react/docs/component-specs.html).
### React.renderComponent
### React.render
```javascript
ReactComponent renderComponent(
ReactComponent component,
ReactComponent render(
ReactElement element,
DOMElement container,
[function callback]
)
```
Render a React component into the DOM in the supplied `container` and return a reference to the component.
Render a ReactElement into the DOM in the supplied `container` and return a reference to the component.
If the React component was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
If the ReactElement was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
If the optional callback is provided, it will be executed after the component is rendered or updated.
> Note:
>
> `React.renderComponent()` replaces the contents of the container node you
> `React.render()` replaces the contents of the container node you
> pass in. In the future, it may be possible to insert a component to an
> existing DOM node without overwriting the existing children.
@ -54,46 +54,38 @@ boolean unmountComponentAtNode(DOMElement container)
Remove a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns `true` if a component was unmounted and `false` if there was no component to unmount.
### React.renderComponentToString
### React.renderToString
```javascript
string renderComponentToString(ReactComponent component)
string renderToString(ReactElement element)
```
Render a component to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
Render a ReactElement to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call `React.renderComponent()` on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
If you call `React.render()` on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
### React.renderComponentToStaticMarkup
### React.renderToStaticMarkup
```javascript
string renderComponentToStaticMarkup(ReactComponent component)
string renderToStaticMarkup(ReactElement element)
```
Similar to `renderComponentToString`, except this doesn't create extra DOM attributes such as `data-react-id`, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.
Similar to `renderToString`, except this doesn't create extra DOM attributes such as `data-react-id`, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.
### React.isValidClass
```javascript
boolean isValidClass(* factory)
```
Verifies the factory is a React class descriptor. See `React.createClass`.
### React.isValidComponent
### React.isValidElement
```javascript
boolean isValidComponent(* object)
boolean isValidElement(* object)
```
Verifies the object is a React component descriptor.
Verifies the object is a ReactElement.
### React.DOM
`React.DOM` provides all of the standard HTML tags needed to build a React app. You generally don't use it directly; instead, just include it as part of the `/** @jsx React.DOM */` docblock.
`React.DOM` provides convenience wrappers around `React.createElement` for DOM components. These should only be used when not using JSX. For example, `React.DOM.div(null, 'Hello World!')`
### React.PropTypes

37
docs/ref-02-component-api.md

@ -8,7 +8,7 @@ next: component-specs.html
## ReactComponent
Instances of a React Component are created internally in React when rendering. These instances are reused in subsequent renders, and can be accessed in your component methods as `this`. The only way to get a handle to a React Component instance outside of React is by storing the return value of `React.renderComponent`. Inside other Components, you may use [refs](/react/docs/more-about-refs.html) to achieve the same result.
Instances of a React Component are created internally in React when rendering. These instances are reused in subsequent renders, and can be accessed in your component methods as `this`. The only way to get a handle to a React Component instance outside of React is by storing the return value of `React.render`. Inside other Components, you may use [refs](/react/docs/more-about-refs.html) to achieve the same result.
### setState
@ -70,48 +70,21 @@ bool isMounted()
`isMounted()` returns true if the component is rendered into the DOM, false otherwise. You can use this method to guard asynchronous calls to `setState()` or `forceUpdate()`.
### transferPropsTo
```javascript
ReactComponent transferPropsTo(ReactComponent targetComponent)
```
Transfer properties from this component to a target component that have not already been set on the target component. After the props are updated, `targetComponent` is returned as a convenience. This function is useful when creating simple HTML-like components:
```javascript
var Avatar = React.createClass({
render: function() {
return this.transferPropsTo(
<img src={"/avatars/" + this.props.userId + ".png"} userId={null} />
);
}
});
// <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`.
> Note:
>
> Use `transferPropsTo` with caution; it encourages tight coupling and makes it easy to accidentally introduce implicit dependencies between components. When in doubt, it's safer to explicitly copy the properties that you need onto the child component.
### setProps
```javascript
setProps(object nextProps[, function callback])
```
When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with `React.renderComponent()`.
When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with `React.render()`.
Though calling `React.renderComponent()` again on the same node is the preferred way to update a root-level component, you can also call `setProps()` to change its properties and trigger a re-render. In addition, you can supply an optional callback function that is executed once `setProps` is completed and the component is re-rendered.
Though calling `React.render()` again on the same node is the preferred way to update a root-level component, you can also call `setProps()` to change its properties and trigger a re-render. In addition, you can supply an optional callback function that is executed once `setProps` is completed and the component is re-rendered.
> Note:
>
> When possible, the declarative approach of calling `React.renderComponent()` again is preferred; it tends to make updates easier to reason about. (There's no significant performance difference between the two approaches.)
> When possible, the declarative approach of calling `React.render()` again is preferred; it tends to make updates easier to reason about. (There's no significant performance difference between the two approaches.)
>
> This method can only be called on a root-level component. That is, it's only available on the component passed directly to `React.renderComponent()` and none of its children. If you're inclined to use `setProps()` on a child component, instead take advantage of reactive updates and pass the new prop to the child component when it's created in `render()`.
> This method can only be called on a root-level component. That is, it's only available on the component passed directly to `React.render()` and none of its children. If you're inclined to use `setProps()` on a child component, instead take advantage of reactive updates and pass the new prop to the child component when it's created in `render()`.
### replaceProps

16
docs/ref-04-tags-and-attributes.md

@ -20,8 +20,8 @@ button canvas caption cite code col colgroup data datalist dd del details dfn
dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5
h6 head header hr html i iframe img input ins kbd keygen label legend li link
main map mark menu menuitem meta meter nav noscript object ol optgroup option
output p param pre progress q rp rt ruby s samp script section select small
source span strong style sub summary sup table tbody td textarea tfoot th
output p param picture pre progress q rp rt ruby s samp script section select
small source span strong style sub summary sup table tbody td textarea tfoot th
thead time title tr track u ul var video wbr
```
@ -52,15 +52,15 @@ For a list of events, see [Supported Events](/react/docs/events.html).
These standard attributes are supported:
```
accept accessKey action allowFullScreen allowTransparency alt async
autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked
accept acceptCharset accessKey action allowFullScreen allowTransparency alt
async autoComplete autoPlay cellPadding cellSpacing charSet checked classID
className cols colSpan content contentEditable contextMenu controls coords
crossOrigin data dateTime defer dir disabled download draggable encType form
formNoValidate frameBorder height hidden href hrefLang htmlFor httpEquiv icon
id label lang list loop max maxLength mediaGroup method min multiple muted
name noValidate open pattern placeholder poster preload radioGroup readOnly rel
required role rows rowSpan sandbox scope scrollLeft scrolling scrollTop
seamless selected shape size span spellCheck src srcDoc srcSet start step
id label lang list loop manifest max maxLength media mediaGroup method min
multiple muted name noValidate open pattern placeholder poster preload
radioGroup readOnly rel required role rows rowSpan sandbox scope scrolling
seamless selected shape size sizes span spellCheck src srcDoc srcSet start step
style tabIndex target title type useMap value width wmode
```

1
docs/ref-08-reconciliation.md

@ -3,6 +3,7 @@ id: reconciliation
title: Reconciliation
permalink: reconciliation.html
prev: special-non-dom-attributes.html
next: glossary.html
---
React's key design decision is to make the API seem like it re-renders the whole app on every update. This makes writing applications a lot easier but is also an incredible challenge to make it tractable. This article explains how with powerful heuristics we managed to turn a O(n<sup>3</sup>) problem into a O(n) one.

192
docs/ref-09-glossary.md

@ -0,0 +1,192 @@
---
id: glossary
title: React (Virtual) DOM Terminology
permalink: glossary.html
prev: reconciliation.html
---
In React's terminology, there are five core types that are important to distinguish:
- [ReactElement / ReactElement Factory](#react-elements)
- [ReactNode](#react-nodes)
- [ReactComponent / ReactComponent Class](#react-components)
## React Elements
The primary type in React is the `ReactElement`. It has four properties: `type`, `props`, `key` and `ref`. It has no methods and nothing on the prototype.
You can create one of these object through `React.createElement`.
```javascript
var root = React.createElement('div');
```
To render a new tree into the DOM, you create `ReactElement`s and pass them to `React.render` a long with a regular DOM `Element` (`HTMLElement` or `SVGElement`). `ReactElement`s are not to be confused with DOM `Element`s. A `ReactElement` is a light, stateless, immutable, virtual representation of a DOM `Element`. It is a virtual DOM.
```javascript
React.render(root, document.body);
```
To add properties to a DOM element, pass a properties object as the second argument and children to the third argument.
```javascript
var child = React.createElement('li', null, 'Text Content');
var root = React.createElement('ul', { className: 'my-list' }, child);
React.render(root, document.body);
```
If you use React JSX, then these `ReactElement`s are created for you. So this is equivalent:
```javascript
var root = <ul className="my-list">
<li>Text Content</li>
</ul>;
React.render(root, document.body);
```
__Factories__
A `ReactElement`-factory is simply a function that generates a `ReactElement` with a particular `type` property. React has a built-in helper for you to create factories. It's effectively just:
```javascript
function createFactory(type){
return React.createElement.bind(null, type);
}
```
It allows you to create a convenient short-hand instead of typing out `React.createElement('div')` all the time.
```javascript
var div = React.createFactory('div');
var root = div({ className: 'my-div' });
React.render(root, document.body);
```
React already have built-in factories for common HTML tags:
```javascript
var root = React.DOM.ul({ className: 'my-list' },
React.DOM.li(null, 'Text Content')
);
```
If you are using JSX you have no need for factories. JSX already provides a convenient short-hand for creating `ReactElement`s.
## React Nodes
A `ReactNode` can be either:
- `ReactElement`
- `string` (aka `ReactText`)
- `number` (aka `ReactText`)
- Array of `ReactNode`s (aka `ReactFragment`)
These are used as properties of other `ReactElement`s to represent children. Effectively they create a tree of `ReactElement`s.
## React Components
You can use React using only `ReactElement`s but to really take advantage of React, you'll want to use `ReactComponent`s to create encapsulations with embedded state.
A `ReactComponent` Class is simply just a JavaScript class (or "constructor function").
```javascript
var MyComponent = React.createClass({
render: function() {
...
}
});
```
When this constructor is invoked it is expected to return an object with at least a `render` method on it. This object is referred to as a `ReactComponent`.
```javascript
var component = new MyComponent(props); // never do this
```
Other than for testing, you would normally __never__ call this constructor yourself. React calls it for you.
Instead, you pass the `ReactComponent` Class to `createElement` you get a `ReactElement`.
```javascript
var element = React.createElement(MyComponent);
```
OR using JSX:
```javascript
var element = <MyComponent />;
```
When this is passed to `React.render`, React will call the constructor for you and create a `ReactComponent`, which returned.
```javascript
var component = React.render(element, document.body);
```
If you keep calling `React.render` with the same type of `ReactElement` and the same container DOM `Element` it always returns the same instance. This instance is stateful.
```javascript
var componentA = React.render(<MyComponent />, document.body);
var componentB = React.render(<MyComponent />, document.body);
componentA === componentB; // true
```
This is why you shouldn't construct your own instance. Instead, `ReactElement` is a virtual `ReactComponent` before it gets constructed. An old and new `ReactElement` can be compared to see if a new `ReactComponent` instance is created or if the existing one is reused.
The `render` method of a `ReactComponent` is expected to return another `ReactElement`. This allows these components to be composed. Ultimately the render resolves into `ReactElement` with a `string` tag which instantiates a DOM `Element` instance and inserts it into the document.
## Formal Type Definitions
__Entry Point__
```
React.render = (ReactElement, HTMLElement | SVGElement) => ReactComponent;
```
__Nodes and Elements__
```
type ReactNode = ReactElement | ReactFragment | ReactText;
type ReactElement = ReactComponentElement | ReactDOMElement;
type ReactDOMElement = {
type : string,
props : {
children : ReactNodeList,
className : string,
etc.
},
key : string | boolean | number | null,
ref : string | null
};
type ReactComponentElement<TProps> = {
type : ReactClass<TProps>,
props : TProps,
key : string | boolean | number | null,
ref : string | null
};
type ReactFragment = Array<ReactNode | ReactEmpty>;
type ReactNodeList = ReactNode | ReactEmpty;
type ReactText = string | number;
type ReactEmpty = null | undefined | boolean;
```
__Classes and Components__
```
type ReactClass<TProps> = (TProps) => ReactComponent<TProps>;
type ReactComponent<TProps> = {
props : TProps,
render : () => ReactElement
};
```

4
docs/thinking-in-react.md

@ -7,7 +7,7 @@ next: videos.html
This was originally a [blog post](/react/blog/2013/11/05/thinking-in-react.html) from the [official React blog](/react/blog).
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.
React is, in my opinion, the premier way to build big, fast Web apps with JavaScript. It has 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.
@ -68,7 +68,7 @@ To build a static version of your app that renders your data model you'll want t
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.
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 `React.render()` 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.

24
docs/tutorial.md

@ -25,7 +25,7 @@ It'll also have a few neat features:
### Getting started
For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your favorite editor and create a new HTML document:
For this tutorial, we'll use prebuilt JavaScript files on a CDN. Open up your favorite editor and create a new HTML document:
```html
<!-- template.html -->
@ -39,8 +39,6 @@ For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your fav
<body>
<div id="content"></div>
<script type="text/jsx">
/** @jsx React.DOM */
// The above declaration must remain intact at the top of the script.
// Your code here
</script>
</body>
@ -77,7 +75,7 @@ var CommentBox = React.createClass({
);
}
});
React.renderComponent(
React.render(
<CommentBox />,
document.getElementById('content')
);
@ -92,14 +90,14 @@ The first thing you'll notice is the XML-ish syntax in your JavaScript. We have
var CommentBox = React.createClass({displayName: 'CommentBox',
render: function() {
return (
React.DOM.div({className: "commentBox"},
React.createElement('div', {className: "commentBox"},
"Hello, world! I am a CommentBox."
)
);
}
});
React.renderComponent(
CommentBox(null),
React.render(
React.createElement(CommentBox, null),
document.getElementById('content')
);
```
@ -114,7 +112,7 @@ The `<div>` tags are not actual DOM nodes; they are instantiations of React `div
You do not have to return basic HTML. You can return a tree of components that you (or someone else) built. This is what makes React **composable**: a key tenet of maintainable frontends.
`React.renderComponent()` instantiates the root component, starts the framework, and injects the markup into a raw DOM element, provided as the second argument.
`React.render()` instantiates the root component, starts the framework, and injects the markup into a raw DOM element, provided as the second argument.
## Composing components
@ -160,7 +158,7 @@ var CommentBox = React.createClass({
});
```
Notice how we're mixing HTML tags and components we've built. HTML components are regular React components, just like the ones you define, with one difference. The JSX compiler will automatically rewrite HTML tags to "React.DOM.tagName" expressions and leave everything else alone. This is to prevent the pollution of the global namespace.
Notice how we're mixing HTML tags and components we've built. HTML components are regular React components, just like the ones you define, with one difference. The JSX compiler will automatically rewrite HTML tags to `React.createElement(tagName)` expressions and leave everything else alone. This is to prevent the pollution of the global namespace.
### Component Properties
@ -280,7 +278,7 @@ var data = [
];
```
We need to get this data into `CommentList` in a modular way. Modify `CommentBox` and the `renderComponent()` call to pass this data into the `CommentList` via props:
We need to get this data into `CommentList` in a modular way. Modify `CommentBox` and the `React.render()` call to pass this data into the `CommentList` via props:
```javascript{7,15}
// tutorial9.js
@ -296,7 +294,7 @@ var CommentBox = React.createClass({
}
});
React.renderComponent(
React.render(
<CommentBox data={data} />,
document.getElementById('content')
);
@ -332,7 +330,7 @@ Let's replace the hard-coded data with some dynamic data from the server. We wil
```javascript{3}
// tutorial11.js
React.renderComponent(
React.render(
<CommentBox url="comments.json" />,
document.getElementById('content')
);
@ -448,7 +446,7 @@ var CommentBox = React.createClass({
}
});
React.renderComponent(
React.render(
<CommentBox url="comments.json" pollInterval={2000} />,
document.getElementById('content')
);

2
downloads.md

@ -71,7 +71,7 @@ If you're using an npm-compatible packaging system like browserify or webpack, y
```js
var React = require('react');
React.renderComponent(...);
React.render(...);
```
If you'd like to use any [add-ons](/react/docs/addons.html), use `var React = require('react/addons');` instead.

BIN
downloads/react-0.11.2.zip

Binary file not shown.

BIN
downloads/react-0.12.0-rc1.zip

Binary file not shown.

BIN
downloads/react-0.12.0.zip

Binary file not shown.

BIN
img/blog/flux-chart.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

BIN
img/blog/reflux-flux.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

4
tips/02-inline-styles.md

@ -10,8 +10,6 @@ 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 + ')',
@ -19,7 +17,7 @@ var divStyle = {
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};
React.renderComponent(<div style={divStyle}>Hello World!</div>, mountNode);
React.render(<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 [other than `ms`](http://www.andismith.com/blog/2012/02/modernizr-prefixed/) should begin with a capital letter. This is why `WebkitTransition` has an uppercase "W".

26
tips/03-if-else-in-JSX.md

@ -10,46 +10,38 @@ 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);
React.render(<div id="msg">Hello World!</div>, mountNode);
// Is transformed to this JS:
React.renderComponent(React.DOM.div({id:"msg"}, "Hello World!"), mountNode);
React.render(React.createElement("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!");
React.createElement("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);
React.render(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
```
If a ternary expression isn't robust enough, you can use `if` statements to determine which
If a ternary expression isn't robust enough, you can use `if` statements to determine which
components should be used.
```js
/** @jsx React.DOM */
var loginButton;
if (loggedIn) {
loginButton = <LogoutButton />;
} else {
loginButton = <LoginButton />;
if (loggedIn) {
loginButton = <LogoutButton />;
} else {
loginButton = <LoginButton />;
}
return (

4
tips/06-style-props-value-px.md

@ -10,10 +10,8 @@ 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);
React.render(<div style={divStyle}>Hello World!</div>, mountNode);
```
See [Inline Styles](/react/tips/inline-styles.html) for more info.

8
tips/07-children-props-type.md

@ -10,8 +10,6 @@ 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
@ -22,7 +20,7 @@ var GenericWrapper = React.createClass({
}
});
React.renderComponent(
React.render(
<GenericWrapper><span/><span/><span/></GenericWrapper>,
mountNode
);
@ -31,8 +29,6 @@ React.renderComponent(
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
@ -47,7 +43,7 @@ var GenericWrapper = React.createClass({
}
});
React.renderComponent(<GenericWrapper>hello</GenericWrapper>, mountNode);
React.render(<GenericWrapper>hello</GenericWrapper>, mountNode);
```
To make `this.props.children` easy to deal with, we've provided the [React.Children utilities](/react/docs/top-level-api.html#react.children).

6
tips/08-controlled-input-null-value.md

@ -14,11 +14,9 @@ You might have run into a problem where `value` is specified, but the input can
The snippet below shows this phenomenon; after a second, the text becomes editable.
```js
/** @jsx React.DOM */
React.renderComponent(<input value="hi" />, mountNode);
React.render(<input value="hi" />, mountNode);
setTimeout(function() {
React.renderComponent(<input value={null} />, mountNode);
React.render(<input value={null} />, mountNode);
}, 1000);
```

12
tips/10-props-in-getInitialState-as-anti-pattern.md

@ -16,8 +16,6 @@ Using props, passed down from parent, to generate state in `getInitialState` oft
**Bad example:**
```js
/** @jsx React.DOM */
var MessageBox = React.createClass({
getInitialState: function() {
return {nameWithQualifier: 'Mr. ' + this.props.name};
@ -28,21 +26,19 @@ var MessageBox = React.createClass({
}
});
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
React.render(<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);
React.render(<MessageBox name="Rogers"/>, mountNode);
```
(For more complex logic, simply isolate the computation in a method.)
@ -50,8 +46,6 @@ React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
However, it's **not** an anti-pattern if you make it clear that synchronization's not the goal here:
```js
/** @jsx React.DOM */
var Counter = React.createClass({
getInitialState: function() {
// naming it initialX clearly indicates that the only purpose
@ -68,5 +62,5 @@ var Counter = React.createClass({
}
});
React.renderComponent(<Counter initialCount={7}/>, mountNode);
React.render(<Counter initialCount={7}/>, mountNode);
```

4
tips/11-dom-event-listeners.md

@ -14,8 +14,6 @@ next: initial-ajax.html
Try to resize the window:
```js
/** @jsx React.DOM */
var Box = React.createClass({
getInitialState: function() {
return {windowWidth: window.innerWidth};
@ -38,7 +36,7 @@ var Box = React.createClass({
}
});
React.renderComponent(<Box />, mountNode);
React.render(<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.

4
tips/12-initial-ajax.md

@ -14,8 +14,6 @@ When processing the response of an asynchronous request, be sure to check that t
This example fetches the desired Github user's latest gist:
```js
/** @jsx React.DOM */
var UserGist = React.createClass({
getInitialState: function() {
return {
@ -46,7 +44,7 @@ var UserGist = React.createClass({
}
});
React.renderComponent(
React.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);

9
tips/13-false-in-jsx.md

@ -12,22 +12,19 @@ Here's how `false` renders in different contexts:
Renders as `id="false"`:
```js
/** @jsx React.DOM */
React.renderComponent(<div id={false} />, mountNode);
React.render(<div id={false} />, mountNode);
```
String `"false"` as input value:
```js
/** @jsx React.DOM */
React.renderComponent(<input value={false} />, mountNode);
React.render(<input value={false} />, mountNode);
```
No child:
```js
/** @jsx React.DOM */
React.renderComponent(<div>{false}</div>, mountNode);
React.render(<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>`.

4
tips/14-communicate-between-components.md

@ -13,8 +13,6 @@ 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]);
@ -33,7 +31,7 @@ var GroceryList = React.createClass({
}
});
React.renderComponent(
React.render(
<GroceryList items={['Apple', 'Banana', 'Cranberry']} />, mountNode
);
```

4
tips/15-expose-component-functions.md

@ -12,8 +12,6 @@ There's another (uncommon) way of [communicating between components](/react/tips
Say a list of todos, which upon clicking get removed. If there's only one unfinished todo left, animate it:
```js
/** @jsx React.DOM */
var Todo = React.createClass({
render: function() {
return <div onClick={this.props.onClick}>{this.props.title}</div>;
@ -55,7 +53,7 @@ var Todos = React.createClass({
}
});
React.renderComponent(<Todos />, mountNode);
React.render(<Todos />, mountNode);
```
Alternatively, you could have achieved this by passing the `todo` an `isLastUnfinishedItem` prop, let it check this prop in `componentDidUpdate`, then animate itself; however, this quickly gets messy if you pass around different props to control animations.

14
tips/16-references-to-components.md

@ -7,24 +7,20 @@ prev: expose-component-functions.html
next: children-undefined.html
---
If you're using React components in a larger non-React application or transitioning your code to React, you may need to keep references to components. `React.renderComponent` returns a reference to the mounted component:
If you're using React components in a larger non-React application or transitioning your code to React, you may need to keep references to components. `React.render` returns a reference to the mounted component:
```js
/** @jsx React.DOM */
var myComponent = React.renderComponent(<MyComponent />, myContainer);
var myComponent = React.render(<MyComponent />, myContainer);
```
Keep in mind, however, that the "constructor" of a component doesn't return a component instance! It's just a **descriptor**: a lightweight representation that tells React what the mounted component should look like.
Keep in mind, however, that the JSX doesn't return a component instance! It's just a **ReactElement**: a lightweight representation that tells React what the mounted component should look like.
```js
/** @jsx React.DOM */
var myComponent = <MyComponent />; // This is just a descriptor.
var myComponentElement = <MyComponent />; // This is just a ReactElement.
// Some code here...
myComponent = React.renderComponent(myComponent, myContainer);
var myComponentInstance = React.render(myComponentElement, myContainer);
```
> Note:

4
tips/17-children-undefined.md

@ -9,8 +9,6 @@ prev: references-to-components.html
You can't access the children of your component through `this.props.children`. `this.props.children` designates the children being **passed onto you** by the owner:
```js
/** @jsx React.DOM */
var App = React.createClass({
componentDidMount: function() {
// This doesn't refer to the `span`s! It refers to the children between
@ -23,7 +21,7 @@ var App = React.createClass({
}
});
React.renderComponent(<App></App>, mountNode);
React.render(<App></App>, mountNode);
```
To access your own subcomponents (the `span`s), place [refs](http://facebook.github.io/react/docs/more-about-refs.html) on them.

Loading…
Cancel
Save