Compare commits

...

238 Commits

Author SHA1 Message Date
Ben Alpert
56517a5423 Blog post for 0.9 release candidate 2014-02-16 19:37:24 -08:00
Ben Alpert
ec58683389 Fix typo in latest round-up 2014-02-15 22:54:32 -08:00
Jonas Gebhardt
be569b1ee1 Add community round-up #16 2014-02-15 15:54:40 -08:00
Paul O’Shannessy
407589bd96 Center twitter embeds differently. again.
This time, just target the iframe. display: table was weird in webkit.
2014-02-05 16:23:43 -08:00
Paul O’Shannessy
084f24e3e7 Don't use <center> for twitter embeds 2014-02-05 15:52:59 -08:00
Jonas Gebhardt
acf97b26ca Community Round-Up #15; center embedded tweets 2014-02-05 15:52:59 -08:00
Paul O’Shannessy
ccf00ccf08 Revert "Update propTypes documentation."
This reverts commit b66fbde0a9.
2014-02-05 15:05:41 -08:00
Pete Hunt
7f22f43fb1 Update example-apps.md 2014-02-02 04:02:17 +01:00
petehunt
92092073ca add example apps page 2014-02-02 04:02:10 +01:00
petehunt
3c19f6253b Add a complementary tools page 2014-02-02 04:01:56 +01:00
Pete Hunt
7467b1fb39 Update videos.md 2014-02-02 04:01:48 +01:00
petehunt
c06ca2305f Add link to meteor talk 2014-02-02 04:01:37 +01:00
Ben Alpert
3810c839a7 [docs] Fix comma splice 2014-02-02 03:51:23 +01:00
Ben Alpert
571d173182 Disable CodeMirror smart indentation
Fixes #966.
2014-02-02 03:51:16 +01:00
Christopher Chedeau
22772c9862 s/Mock DOM/Virtual DOM/
Let's be consistent with the naming
2014-02-02 03:51:07 +01:00
Kunal Mehta
f9704536d1 Add documentation about React.renderComponent
Recently learned that components passed into `React.renderComponent` may not be the ones actually mounted. Also learned that it returns the mounted component. Added some documentation describing this.
2014-02-02 03:50:58 +01:00
Eric Schoffstall
64ac427395 fix grammar mistake 2014-02-02 03:50:26 +01:00
Paul O’Shannessy
dd66223d67 Fix animation example code
key should never be index into an array or there are bugs. Especially in
transitions.

Fixes #853
2014-02-02 03:49:58 +01:00
Ben Alpert
6e4ddfd239 Fix docs typo 2014-02-02 03:49:48 +01:00
petehunt
3120192172 remove references to react-page 2014-02-02 03:49:41 +01:00
Bob Eagan
3db3460868 add hash link for lifecycle section of working with the browser page 2014-02-02 03:49:14 +01:00
Bob Eagan
2edb76f558 fix incorrect link 2014-02-02 03:48:41 +01:00
Ayman Osman
09650e1dc3 Fix typo 2014-02-02 03:47:54 +01:00
Jean Lauliac
0681d1386b Normalize internal links in 'why react' article 2014-02-02 03:47:16 +01:00
Jean Lauliac
341d292665 Update broken link in 'why react' article 2014-02-02 03:47:01 +01:00
cpojer
b66fbde0a9 Update propTypes documentation. 2014-02-02 03:46:42 +01:00
Cheng Lou
8c8841c83a [docs] Tweak frontpage first example and jsx-compiler example 2014-02-02 03:45:31 +01:00
Ben Alpert
c7f0663176 Simplify live editor execution logic 2014-02-02 03:45:21 +01:00
Ben Alpert
d3fc5adf39 Properly clear live editor on JSX compile failure 2014-02-02 03:45:15 +01:00
Ben Alpert
761e1c8080 Update homepage for new JSX/JS editor 2014-02-02 03:44:58 +01:00
Paul O’Shannessy
6b1c6be974 Normalize line endings 2014-02-02 03:44:44 +01:00
Cheng Lou
7ac5f3c7cf docs add jsx->js tab to live editors 2014-02-02 03:43:43 +01:00
Cheng Lou
6b15ad5f6d docs fix back link in Examples 2014-02-02 03:43:26 +01:00
Nick Thompson
542f20b822 Clarify componentWillMount behavior 2014-02-02 03:42:40 +01:00
Christopher Chedeau
30e16e4e63 Document isMounted
Text from @petehunt
2014-02-02 03:42:15 +01:00
Paul O’Shannessy
7c4c0cdd01 [docs] Remove commented out ghbtns 2014-01-15 11:39:52 -08:00
Ben Alpert
92102ac31d Add info about dev vs. prod builds
Also moved the dev builds first because that's what most people will want.
2014-01-15 11:35:51 -08:00
Paul O’Shannessy
277cbf06e4 [docs] Add timezone to _config
This way we hopefully won't churn the feed when genereated in
a different time zone (eg France).
2014-01-15 11:12:02 -08:00
Paul O’Shannessy
b0b771763b Remove stray "117", combine lines in polyfill docs 2014-01-15 11:09:24 -08:00
Richard Feldman
8d63dad433 Rewrite Older Browsers polyfill section for clarity. 2014-01-15 10:52:39 -08:00
Timothy Yung
edd61edfb1 Fix "Uncontrolled Components" documentation 2014-01-15 10:52:38 -08:00
Richard Feldman
d99cafaf9a Fix typo in docs. 2014-01-15 10:52:38 -08:00
Richard Feldman
190f373ce3 Update docs to mention that you need both es5-shim.js and es5-sham.js to use React with IE8. 2014-01-15 10:52:38 -08:00
Ben Alpert
1873e1d0a9 Add dataType to all $.ajax calls for consistency
Fixes https://groups.google.com/forum/#!topic/reactjs/WWA3ZqU6y4w.
2014-01-15 10:52:38 -08:00
Christoph Pojer
27ac8a3224 Fix #845, Trivial year change
This was accidentally pulled into gh-pages.
2014-01-15 10:52:38 -08:00
Christoph Pojer
97f2441b7e Fix #874: Edit thinking-in-react
Accidentally pulled #874 into gh-pages.
2014-01-15 10:52:38 -08:00
Ben Alpert
ce72e84234 Document return value of unmountComponentAtNode 2014-01-15 10:52:38 -08:00
Ben Alpert
52ad24f788 Remove two more react.min.js references 2014-01-15 10:52:38 -08:00
Paul O’Shannessy
7efdb43742 Don't use the min build in getting started guide 2014-01-15 10:52:38 -08:00
Michal Srb
51e7a6bae1 Fix URL in displayName description 2014-01-15 10:52:38 -08:00
Ben Alpert
f44e8ccd40 Add charCode/keyCode/which to key event docs 2014-01-15 10:52:38 -08:00
Vjeux
60b5520fee Revert "adding warning about the lack of support for onScroll on IE8"
This reverts commit 8615ade2b6.
2014-01-06 18:35:50 +01:00
Vjeux
658aa45483 Community Round-up #14 2014-01-06 18:15:56 +01:00
Daniel Lo Nigro
ea41991825 Change “not allowed” back to “discouraged” since you technically *can* use props called class or for 2014-01-06 18:15:24 +01:00
Daniel Lo Nigro
5cbc727f68 Add link to HTML to JSX converter to “JSX In Depth” page 2014-01-06 18:15:19 +01:00
xixixao
ee90857dfb Document displayName 2014-01-06 18:15:13 +01:00
Pascal Hartig
8ef2cec2c4 Add gulp-react to Helpful OSS Projects
Add @sindresorhus' JSX task for Gulp to the "Helpful Open-Source Projects" section of the tooling integration docs.
2014-01-06 18:15:07 +01:00
Ben Alpert
3afe6dee51 Fix typo 2014-01-06 18:14:59 +01:00
Ben Alpert
13c211a6a6 Mention react-art where we talk about SVG 2014-01-06 18:14:50 +01:00
Felipe Oliveira Carvalho
e23e627091 Remove the require-jsx plugin from the tooling-integration page
In favor of the r.js friendly jsx-requirejs-plugin
2014-01-06 18:14:40 +01:00
Felipe Oliveira Carvalho
978a8f5807 Add jsx-requirejs-plugin to the tooling-integration page 2014-01-06 18:14:31 +01:00
Fabio Costa
8615ade2b6 adding warning about the lack of support for onScroll on IE8
Adding `console.warn` about the lack of support for `onScroll` event on IE8
Related to this issue on github https://github.com/facebook/react/issues/631
2014-01-06 18:14:02 +01:00
Vjeux
dbae31d36f React Chrome Developer Tools 2014-01-02 21:05:37 +01:00
Cheng Lou
8d37f7d373 docs better error display for live editor and JSX compiler 2014-01-02 21:05:27 +01:00
Cheng Lou
8dc36e396b docs tips fix small typo and code 2014-01-02 21:05:20 +01:00
Cheng Lou
c5a2ca997c docs remove link to wiki page
Also some minor writing changes.
2013-12-31 05:59:08 +01:00
Ben Alpert
32753c59d4 Upgrade codemirror and enable line wrapping
Fixes #678.
2013-12-31 05:58:46 +01:00
Vjeux
16072437c3 Making 'native DOM' nodes more explicit in documentation 2013-12-31 01:38:22 +01:00
Ben Alpert
5e441d656f IE8 style fixes
- Add html5shiv so that HTML5 elements like header, footer, etc can be styled
- Remove a couple uses of :first-child/:last-child which IE8 doesn't support
2013-12-31 01:25:10 +01:00
Cheng Lou
0b63c665eb docs tips small refactorings 2013-12-31 00:13:10 +01:00
Ben Alpert
30178d4baf Make React website work in IE8
Fixes #406.

Empty conditional comment is for http://www.phpied.com/conditional-comments-block-downloads/.
2013-12-30 23:46:55 +01:00
Wincent Colaiuta
0e95e8e76d Fix a typo in the working-with-the-browser docs 2013-12-30 23:44:07 +01:00
Cheng Lou
cdb328be92 docs tips expose component function 2013-12-30 23:43:30 +01:00
jhiswin
4b7eb66b31 live_editor.js using deprecated function
unmountAndReleaseReactRootNode -> unmountComponentAtNode
breaks html-jsx.html
2013-12-30 19:57:41 +01:00
petehunt
b55ebc0a95 Update parent/child communication tip 2013-12-30 19:45:40 +01:00
Vjeux
3a370b8db5 Community Round-up #13 2013-12-30 18:30:56 +01:00
Ben Alpert
12b94b0a8c Move initial $.ajax out of getInitialState
We want to encourage people to make pure getInitialState functions.
2013-12-30 18:30:48 +01:00
Ivan Kozik
880951f08c console.log -> console.error 2013-12-30 18:30:12 +01:00
Ivan Kozik
838589c37a Add a warning about the @jsx declaration 2013-12-30 18:30:07 +01:00
Ivan Kozik
0ae26fed60 Use explicit $.ajax dataType and add error callback 2013-12-30 18:30:00 +01:00
Cheng Lou
c68b972618 docs add warning to add jsx pragma 2013-12-30 18:29:53 +01:00
Cheng Lou
a35671a6ec docs remove video at the bottom 2013-12-24 07:45:37 +01:00
Vjeux
5a571e0777 Add a talks section to the docs 2013-12-24 01:31:56 -05:00
Fabio M. Costa
645e25d7a8 language update as suggested by @petehunt 2013-12-24 00:49:19 -05:00
Fabio M. Costa
fa42d0cc6d updating text as suggested by @petehunt 2013-12-24 00:49:11 -05:00
Fabio M. Costa
0a8c2bb272 Adding note about onScroll on IE8 2013-12-24 00:49:06 -05:00
Fabio M. Costa
8de5a925fa Note about react's version on the talk, since somethings have already changed since then 2013-12-24 00:48:57 -05:00
Vjeux
14e05c9dbb typo 2013-12-23 18:54:16 +01:00
Vjeux
219f25c812 Fix html-jsx compiler
It changed React Playground to add a required props but unfortunately didn't update the call sites of the front-page. I don't think it should be required so I'm just making it optional and providing the correct default value.

Test Plan:
 - Open the front page and make sure examples are working
 - Open /react/jsx-compiler.html and make sure it is working
 - Open /react/html-jsx.html and make sure it is working
2013-12-23 18:32:13 +01:00
Daniel Lo Nigro
c7a915993e Simple HTML to JSX converter, built during Hackathon 40 at Facebook.
See /react/html-jsx.html. Not directly linked from the site yet as there may still be some minor issues with it.
2013-12-23 18:32:04 +01:00
Vjeux
6d822d4149 Community Round-up #12 2013-12-23 18:04:55 +01:00
Vjeux
b95fee3c0b Revert "Simple HTML to JSX converter, built during Hackathon 40 at Facebook."
This reverts commit 2308f95316.
2013-12-23 07:01:12 +01:00
Daniel Lo Nigro
2308f95316 Simple HTML to JSX converter, built during Hackathon 40 at Facebook.
See /react/html-jsx.html. Not directly linked from the site yet as there may still be some minor issues with it.
2013-12-23 06:14:39 +01:00
Cheng Lou
dbc8563dfb docs make all link start with /react/docs 2013-12-23 06:14:32 +01:00
Cheng Lou
7eae8d3c4a docs add input attrs for Dom Differences 2013-12-23 06:14:00 +01:00
Kit Randel
37e544d817 Tutorial template markup needs a reference to jquery for the ajax calls
from step 13 onwards.
2013-12-23 06:12:45 +01:00
Jared Forsyth
cd2fd806dc one liner 2013-12-23 06:12:38 +01:00
Jared Forsyth
cb0cbcc305 changes as requested 2013-12-23 06:12:33 +01:00
Jared Forsyth
4f71ddfe5f adding note about initializing state w/ props 2013-12-23 06:12:27 +01:00
Nicholas Bergson-Shilcock
18410bf130 Fix typo (ot -> to) 2013-12-23 06:11:21 +01:00
Jared Forsyth
1a9b21313e fixing capitalization 2013-12-23 06:11:10 +01:00
Jared Forsyth
9686487e3a rename this tip to be less confusing
Using props to initialize state is completely fine; the issue is using state as a "cache" for values calculated based off of props. This title makes it more clear.
2013-12-23 06:11:03 +01:00
Brian Cooke
38d68fd1c5 Update highlighted lines in tutorial
Minor issue, but I found it distracting that the highlighted lines were not accurate. I *believe* this fixes them up.
2013-12-23 06:10:40 +01:00
Vjeux
0993b61fe8 Add video at the bottom of the front page 2013-12-23 06:10:23 +01:00
Vjeux
8f24fcae05 Document the Diff algorithm
We often refer to it but never did actually explain it.
2013-12-23 06:04:47 +01:00
Cheng Lou
94c100cc7a docs section for non-dom attributes
Also added documentation for `dangerouslySetInnerHTML`.
2013-12-23 06:04:42 +01:00
Paul O’Shannessy
b9579e444b 0.8 starter kit 2013-12-19 13:16:07 -08:00
Paul O’Shannessy
4630540f87 v0.8 blog post 2013-12-19 10:42:22 -08:00
Paul O’Shannessy
ece573e7fe Update materials for 0.8.0 2013-12-19 10:41:49 -08:00
Paul O’Shannessy
2e1e868080 v0.8.0 2013-12-19 10:41:03 -08:00
Paul O’Shannessy
e78b01f090 Fix npm-react build task, add to release 2013-12-19 10:31:43 -08:00
Paul O’Shannessy
c7562cf924 Update AUTHORS for 0.8 2013-12-19 09:35:17 -08:00
Paul O’Shannessy
b90ec8a8ec Add newest starter-kit downloads to docs 2013-12-18 17:01:30 -08:00
Paul O’Shannessy
b4cc540a7b Add starter-kit zip files to repo
These should be included so that anybody can build and update the docs
with as little confusion as possible.

I've left the directory in .gitignore so additions need to be
intentional as part of a release.
2013-12-18 17:01:30 -08:00
Paul O’Shannessy
76dc1f7661 Changelog, blog post for 0.5.2, 0.4.2 2013-12-18 16:46:31 -08:00
Paul O’Shannessy
e9b8edd4ba Update readme for 0.5.2 2013-12-18 16:46:31 -08:00
Paul O’Shannessy
0c05167b33 Update npm-react error to point to autoflow 2013-12-17 11:22:07 -08:00
Paul O’Shannessy
77bd2cc1f3 Update npm-react readme to point to autoflow 2013-12-17 11:22:07 -08:00
Paul O’Shannessy
102e1d1fb3 Don't call utils.traverse in transform
Accidental change we missed in review of #495.
2013-12-17 11:10:23 -08:00
Andreas Svensson
50979ffa9e utils.* is now used everywhere 2013-12-17 11:10:23 -08:00
Andreas Svensson
65818f9716 JSXTransformer now supports IE8
Conflicts:
	package.json
2013-12-17 11:10:20 -08:00
Thomas Aylott
65026b1008 fixes ReactTextComponent rootID unescapedness 2013-12-17 10:45:01 -08:00
Thomas Aylott
c24efdba9c test case for ReactTextComponent rootID escaping 2013-12-17 10:45:01 -08:00
Fabio M. Costa
dba52065c9 URL -> url 2013-12-17 10:45:01 -08:00
Josh Duck
7f156bebbf Fix SelectEventPlugin
mouseup was not fired when context menu showed, so select events stopped being fired.
2013-12-17 10:45:01 -08:00
Ben Alpert
8048f96b42 Add loop property 2013-12-17 10:45:01 -08:00
Fabio M. Costa
17b456cfee match -> test
Using RegExp method `test` because this is what is wanted
2013-12-17 10:45:01 -08:00
Fabio M. Costa
432109783a Improving never seen error message
Removing repeating "support it" and fixing camelCase method name
2013-12-17 10:45:01 -08:00
Paul O’Shannessy
93fc40c680 Clean trailing space and lint 2013-12-17 10:45:01 -08:00
Andreas Svensson
fb656ad9ab corrections 2013-12-17 10:45:01 -08:00
Andreas Svensson
36cf618ee7 Fix ReactDOMTextarea missing "rows" and "cols" attribute, incorrect "size" property 2013-12-17 10:45:01 -08:00
Andreas Svensson
68edaa3cfd Add HAS_POSITIVE_NUMERIC_VALUE to DOMProperty and normalize behavior of null values
Uniformly remove null values, rather than sometimes set/remove, could potentially assign 'null' or 'undefined'
2013-12-17 10:45:01 -08:00
Paul O’Shannessy
6235c6b346 Update shrinkwrap 2013-12-13 15:17:26 -08:00
Thomas Aylott
1bf4de4110 fixes browserify task transforms support 2013-12-13 15:08:38 -08:00
Paul O’Shannessy
57b34a120e Move npm-react-core to npm-react, fix tasks accordingly 2013-12-13 14:24:14 -08:00
Paul O’Shannessy
d0be71c8f3 Update react package readme 2013-12-13 14:24:14 -08:00
petehunt
c278a788ac Version bump, make tests work
Conflicts:
	grunt/tasks/populist.js
	package.json
	src/core/React.js
2013-12-13 14:24:11 -08:00
petehunt
1dd0ae5eb7 update README 2013-12-13 14:15:57 -08:00
petehunt
207f2ddb00 version bump to 0.8 to get on top of react.js
Conflicts:
	package.json
2013-12-13 14:15:54 -08:00
petehunt
1188ba5047 rename to with associated warnings 2013-12-13 14:14:42 -08:00
petehunt
caebca54b8 rename to with associated warnings 2013-12-13 14:14:42 -08:00
petehunt
39b7ba2842 revert muffinize :( 2013-12-13 14:14:42 -08:00
petehunt
280243f28b response to code review 2013-12-13 14:14:42 -08:00
petehunt
5361a2bc92 update npm-react-core package.json 2013-12-13 14:14:42 -08:00
Paul O’Shannessy
4262a4089e react-core npm module 2013-12-13 14:14:42 -08:00
petehunt
66b7a5ba0c muffinification 2013-12-13 14:14:42 -08:00
petehunt
0d69d37d06 first work: __DEV__
fix invariant

Get browserify working

remove dead code elimination step since it is not needed due to minifier

use industry standard NODE_ENV

Conflicts:
	grunt/config/browserify.js
	package.json
2013-12-13 14:14:40 -08:00
Ben Newman
92fd516ab8 Explicitly require the assert module in vendor/constants.js. 2013-12-13 14:12:45 -08:00
Ben Newman
0b584b9f8e Better comments for vendor/constants.js. 2013-12-13 14:12:45 -08:00
Ben Newman
1d9a0ce7ff Rewrite vendor/constants.js to use require("ast-types").traverse.
Most notably, this new style of transformation gives us access to
this.parent.node, which allows us to avoid replacing identifiers that are
not actually free variables, such as member expression properties.

Closes #496.

Conflicts:
	package.json
2013-12-13 14:11:22 -08:00
Paul O’Shannessy
a426f1f216 Update depedencies 2013-12-13 13:46:48 -08:00
Paul O’Shannessy
107fbfa809 Disable AnalyticsEventPlugin-test
It gets stuck in web worker issues for some reason. I don't particularly
care and I don't think any of the changes we merged in should be
actually breaking it.
2013-12-13 13:44:35 -08:00
Thomas Aylott
c93db82538 skip Worker test unless the browser supports them 2013-12-12 16:38:05 -08:00
Sean Kinsey
f1a4b84e4c [ReactTransitionGroup] Add onTransitionEnter and onTransitionLeave
It is valuable to know when the number of children in a TransitionGroup is going
to increase or decrease, since we might want to apply extra animations.
For instance, when used with overflow:auto, we might want to apply different css
based on it overflowing or not - to do this we need to calculate this after new
nodes has entered and after nodes has been removed.
2013-12-12 16:01:50 -08:00
John Watson
6438a87264 Separate replaceState invariant violations
It'd be nice if we knew which error we were hitting when this invariant hit.
2013-12-12 16:01:50 -08:00
Ben Alpert
8cb528f0d3 Remove unused updatePropertiesByID 2013-12-12 16:01:50 -08:00
Pete Hunt
656e1bd1b1 Fix lint warnings 2013-12-12 16:01:50 -08:00
Ben Alpert
b0a8103668 Add missing license header 2013-12-12 16:01:49 -08:00
Ben Alpert
7c702fd312 Remove unused event plugin registrationNamesKeys 2013-12-12 16:01:49 -08:00
Ben Alpert
52c7c95be6 ReactErrorUtils: In prod, just return the original
This will save a stack frame (nice when in a debugger) and presumably be a bit faster.
2013-12-12 16:01:49 -08:00
Ben Alpert
b6c7300d48 Don't use .returnValue if .defaultPrevented exists
`.defaultPrevented` exists in IE9+. I checked in IE9, Chrome, and Firefox that it does default to `false`.

Fixes #527.
2013-12-12 16:01:49 -08:00
Christoph Pojer
bc219a2d6e Ensure ReactPerf always uses a string as a URL 2013-12-12 16:01:49 -08:00
Paul O'Shannessy
ad693d9541 order object properties consistently 2013-12-12 16:01:49 -08:00
Pete Hunt
2d5142bc35 Better error message for renderComponentToString()
Reported on Twitter by AirBnb (who are integrating React into their open-source JS framework). They made a mistake and passed a string in as the
component. We should have a better error message for that.
2013-12-12 16:01:49 -08:00
Marshall Roch
6f9f371d2b Rename receiveProps to receiveComponent
This renames receiveProps and changes it to take the next component to copy props from instead of just the props. That is,

  component.receiveComponent(nextComponent, transaction)

instead of

  component.receiveProps(nextComponent.props, transaction)

This is a precursor to adding contexts, which will also need to get propagated just like props. This change allows ReactCompositeComponent to override `receiveProps` and do something like

  this._pendingContext = nextComponent.context;

Conflicts:
	src/core/ReactCompositeComponent.js
2013-12-12 16:01:43 -08:00
Simon Højberg
9e9b3f7348 Transitions: Handle undefined input to mergeKeySet
Gracefully handle undefined input to mergeKeySet.
2013-12-12 15:58:54 -08:00
Simon Højberg
012ac24728 ReactTransitions: Don't animate undefined children 2013-12-12 15:58:54 -08:00
Brian Kim
4915a63973 Fix failing tests
Two of your tests were failing because of commit
1e71df5399
I fixed them by:
1) Using jasmine's spyOn in ReactCompositeComponentError-test.js
2) Inverting the function wrapping in the above commit.
Godspeed.
2013-12-12 15:58:54 -08:00
Tim Yung
55c5178a55 Rename nodeContains to containsNode
Conflicts:
	src/core/ReactMount.js
2013-12-12 15:58:51 -08:00
Mouad Debbar
f142b9b99b Add support for oncontextmenu in React. 2013-12-12 15:57:00 -08:00
Felix Kling
4eb9487c97 Improve error logging for event handlers of React components.
This guards every auto-bound method and uses the name of the component and method as guard name.
2013-12-12 15:57:00 -08:00
Andreas Svensson
3f31ee8d3c Fix wheelDelta misspelled 2013-12-12 15:57:00 -08:00
Ben Alpert
89480e9f38 Make submit button default value appear correctly
Fixes #473.
2013-12-12 15:57:00 -08:00
SanderSpies
4361fb36f9 Removing 'isEventSupported' 2013-12-12 15:57:00 -08:00
SanderSpies
e1fce03d64 Removing unused useSelect variable. 2013-12-12 15:57:00 -08:00
Laurence Rowe
0b4f89cecb Script async and defer properties 2013-12-12 15:57:00 -08:00
Paul O’Shannessy
c09bc39a34 Oxford comma 2013-12-12 15:57:00 -08:00
Josh Duck
996cda82e1 Fix ReactDOMSelection for IE 11
IE 11 no longer supports the legacy document.selection API.
Their implementation of window.getSelection() doesn't support
the extend() method, which we were relying on.

If the selection is RTL and selection extend is missing, then just
flip the selection.
2013-12-12 15:57:00 -08:00
Matti Nelimarkka
efa3618955 Clear error message when rendering a nonvalid component 2013-12-12 15:57:00 -08:00
Tim Yung
c6d2f06697 Better getUnboundedScrollPosition for windows
Instead of using browser sniffing, `getUnboundedScrollPosition` can do
better and not have to depend on the `getDocumentScrollElement` module.
2013-12-12 15:56:59 -08:00
Paul O'Shannessy
06edb20cdf Reorder DefaultDOMPropertyConfig
`autoCorrect` belongs with the non-standard properties list.
2013-12-12 15:56:59 -08:00
Mark Richardson
f4da9418f2 Add autoCorrect to list of supported DOM properties 2013-12-12 15:56:59 -08:00
Tim Yung
7ecd72e724 Forward Compatibility w/ WebKit & Blink
Newer versions of WebKit and Blink will support both `document.body.scrollTop` and `document.documentElement.scrollTop`. Therefore, implementing cross-browser compatibility by summing the two will no longer work.

This changes React to use `getUnboundedScrollPosition` so we get the fix and consistency in one change!

See: https://rniwa.com/2013-10-29/web-compatibility-story-of-scrolltop-and-scrollleft/
2013-12-12 15:56:59 -08:00
Cheng Lou
48af9c7bda docs tips parent-child communication 2013-12-02 15:49:27 -08:00
Paul O’Shannessy
1da10d718d Fix blog pagination
I missed this in the Jekyll upgrade.
2013-12-02 15:47:21 -08:00
Paul O’Shannessy
ef8bd04b04 [docs] Fix download links to addons builds 2013-12-02 15:14:52 -08:00
Pete Hunt
030835b914 Merge pull request #440 from petehunt/new-taglines
New marketing copy
2013-12-02 15:10:24 -08:00
Ben Alpert
abf199d5ff Tweaks to README
Most significant change is updating the leading copy to match #440.
2013-12-02 15:10:12 -08:00
petehunt
1053a1453a Fix frontpage example to retain selection 2013-12-02 15:10:12 -08:00
Cheng Lou
b8194d92f6 docs add download links for react-with-addons 2013-12-02 15:10:12 -08:00
Cheng Lou
18a6b0b94b make docs jsx compiler highlight transpiled js code 2013-12-02 15:10:12 -08:00
Sundeep Malladi
0b31175238 Minor spelling correction in docs 2013-12-02 15:10:12 -08:00
Cheng Lou
6a0bb61b16 docs select value to control chosen option 2013-12-02 15:10:12 -08:00
Ben Alpert
c065b03b8a autoBind -> Autobinding
We don't use the term autoBind anywhere any more.
2013-12-02 15:10:12 -08:00
Levi McCallum
c32c788e5a Add explination of autoBind to DOM Event Listener tip 2013-12-02 15:10:12 -08:00
Paul O’Shannessy
4a0a14d319 Put nav data in "_data"
New in Jekyll 1.3 - http://jekyllrb.com/docs/datafiles/
2013-11-20 23:34:10 -08:00
Paul O’Shannessy
a55d44efaf Fix pagination 2013-11-20 23:34:10 -08:00
Paul O’Shannessy
08fcec503c Update jekyll to 1.3 2013-11-20 23:34:10 -08:00
Cheng Lou
cd6d43e4c0 docs highlight className and htmlFor transforms 2013-11-19 23:28:27 +01:00
Cheng Lou
c329eb6335 docs classSet semicolons missing 2013-11-19 23:28:27 +01:00
Paul O’Shannessy
215988f879 Merge branch 'chenglou-classSet'
closes #463
2013-11-19 23:27:40 +01:00
Ben Alpert
fb7e157cba Make doc headers clickable again
...without preventing clicks on other things.

Just use an `<a name="...">` tag that doesn't take up any space to make sure that we're not covering up something else.

For whatever reason, doing `position: relative; top: -$navHeight;` doesn't work and causes the anchor target not to be moved up. This solution works in both Chrome and Firefox.
2013-11-19 23:24:49 +01:00
Vjeux
8ead6dce76 Community round-up #11 2013-11-19 22:57:46 +01:00
Paul O’Shannessy
79b09d9597 Merge pull request #362 from mcsheffrey/feat-documentation-cookbook
React Tips documentation
2013-11-14 15:06:05 -08:00
Cheng Lou
fb1a072739 fix doc & example transition opacity from .99 to 1
The initial thought was that an opacity animation from 0.01 to 1 causes trouble on some browser. But after testing on opera 12.15, ff 23, ie 10, chrome 30, desktop/mobile safari 7 and chrome android I confirm this works.
2013-11-13 17:55:03 -08:00
Pieter Vanderwerff
c1c7a601dd Added clearfix to blog content holder 2013-11-13 17:54:31 -08:00
Fabio M. Costa
adad0d72be Fixes the name of the component on documentation
AvatarImage -> Avatar
2013-11-13 17:54:02 -08:00
Guido Bouman
e7f48a6c00 Prevents header anchors from interfering with clickable content. 2013-11-13 17:54:02 -08:00
petehunt
d3cee1ee2e Make state immutable in tutorial (eek) 2013-11-08 13:31:45 -08:00
Cheng Lou
d47d509637 move docs tooling from JSX in Depth
Also removes the code wrap around the syntax highlighting link.
2013-11-08 13:31:34 -08:00
Vjeux
411419c361 Community round-up #10 2013-11-06 12:44:42 -08:00
Ben Alpert
fc67d5544c Use smaller blog images and host directly 2013-11-06 12:44:25 -08:00
Andrey Popp
4faad1a32a "Thinking in React": fix list formatting 2013-11-05 16:16:18 -08:00
Paul O’Shannessy
01b40d84c7 Move header link styling out of documentation only
It's used in blog posts too. I also constrained it to just the anchor
class to avoid any other headers we have.
2013-11-05 15:06:58 -08:00
Paul O’Shannessy
67d0f15d1a Remove jQuery version number from tutorial docs 2013-11-05 14:42:46 -08:00
Ben Alpert
e5f03ae407 tutorial: Simplify ajax options
dataType was unnecessary; mimeType was both unnecessary and wrong in this case. Also removed an unnecessary bind and changed pollInterval to 2000 ms for consistency with https://github.com/petehunt/react-tutorial (faster is nicer if you actually try it out!).
2013-11-05 14:42:46 -08:00
Pete Hunt
25140e5a0d "Thinking in React" blog post 2013-11-05 14:41:15 -08:00
Paul O’Shannessy
b5804fa565 [docs] Clarify when getInitialState is called. 2013-11-04 17:21:56 -08:00
petehunt
1bb2651660 Update tutorial to use className 2013-11-04 17:21:28 -08:00
Ben Alpert
b21cdac9e3 Move heading anchors 50px up to avoid nav bar
Fixes #447.

We do this by moving the actual anchored element up in the page without moving the actual text. (Apple uses a similar trick in their framed docs.) Now this looks a bit sillier on smaller screens but it's better overall.
2013-11-04 17:21:16 -08:00
Paul O’Shannessy
92ce80cf4f blog post for 0.5.1 2013-10-29 12:52:00 -07:00
Paul O’Shannessy
f3db0006e8 Update everything for v0.5.1 2013-10-29 11:46:46 -07:00
Paul O’Shannessy
ef4d7a37f0 npm shrinkwrap
We should be doing this in the stable branch to ensure fuzzy
dependencies are met identically on subsequent releases.

In this case, browserify had a change in 2.34.3 which resulted in
JSXTransformer to be a different size. While it was a change for the
better, it was unexpected and not a change we were calling out in the
release.

This shrinkwraps to the same versions of packages we had when we shipped
0.5.0.
2013-10-29 11:46:46 -07:00
Laurence Rowe
64016811d3 Make 'disabled' MUST_USE_ATTRIBUTE for compatibility with CSS [disabled] selectors.
When a ReactDOMComponent is created with the property `disabled: true` subsequently setting the property to `disabled: false` the HTML attribute `disabled="true"` was being left in the DOM.
2013-10-29 10:16:04 -07:00
Andrey Popp
7b957c880c Fix unmounting components mounted into doc element
If we are to unmount a component mounted into a document element we should
unmount it from document.documentElement and not from document.firstChild which
is a doctype element in this specific case.
2013-10-29 10:16:04 -07:00
Ian Obermiller
1b835fb5cf Fix ReactTransitionEvents detectEvents 2013-10-29 10:16:04 -07:00
Cat Chen
9f0bbce797 fixed %d in invariant call 2013-10-29 10:16:04 -07:00
Josh Duck
c9d20e56d3 Don't reset mouseDown in focus handlers
Focus fires after mouse down on initial click, so we lost the
flag when the user initially began dragging on the input.
2013-10-29 10:16:04 -07:00
Ben Alpert
ce612904ef Make SelectEventPlugin not throw for range inputs
Accessing .selectionStart on a non-text input will throw (see http://www.w3.org/TR/2009/WD-html5-20090423/editing.html#textFieldSelection), so check that the input has selection capabilities before accessing the property.

Fixes #437.
2013-10-29 10:16:04 -07:00
Paul O’Shannessy
ea1ab5501d Update API docs for unmountAndReleaseReactRootNode 2013-10-26 17:45:03 -07:00
Brian Rue
2c35ed8068 ReactTransitionGroup example: fix typo and logic bug in handleRemove 2013-10-25 18:25:14 -07:00
Keito Uchiyama
c994cc24c3 docs: Delete Mutation Events (onCharacterDOMModified) 2013-10-25 18:24:37 -07:00
Paul O’Shannessy
24da1c0023 docs: remove OUTLINE 2013-10-21 15:20:46 -07:00
Cheng Lou
d82181e4b9 Add clickable anchors to docs headers
Closes #434
2013-10-21 14:38:57 -07:00
Paul O’Shannessy
ba166b9652 Fix live editor examples on home page.
Remember that one time I wrote release notes and said:

> This is a breaking change - if you were using class, you must change
> this to className or your components will be visually broken.

Good thing I didn't listen to myself!
2013-10-16 18:11:10 -07:00
Paul O’Shannessy
f756cb3d9c 0.5.0 release
Updated README, CHANGELOG, blog post
2013-10-16 11:44:37 -07:00
Paul O’Shannessy
cadf8b786c Fix grunt npm:test 2013-10-16 11:44:37 -07:00
Paul O’Shannessy
953947a617 bump version for 0.5 2013-10-15 22:32:20 -07:00
183 changed files with 9145 additions and 2978 deletions

8
.gitignore vendored
View File

@@ -13,13 +13,7 @@ docs/code
docs/_site
docs/.sass-cache
docs/css/react.css
docs/js/.module-cache
docs/js/JSXTransformer.js
docs/js/react.min.js
docs/js/docs.js
docs/js/jsx-compiler.js
docs/js/live_editor.js
docs/js/examples
docs/js/*
docs/downloads
examples/shared/*.js

18
AUTHORS
View File

@@ -1,12 +1,16 @@
Alexander Solovyov <alexander@solovyov.net>
Andreas Svensson <andreas@syranide.com>
Andrew Zich <azich@fb.com>
Andrey Popp <8mayday@gmail.com>
Ben Alpert <spicyjalapeno@gmail.com>
Ben Newman <bn@cs.stanford.edu>
Brian Kim <briankimpossible@gmail.com>
Brian Rue <brian@rollbar.com>
Cam Spiers <camspiers@gmail.com>
Cat Chen <catchen@fb.com>
Cheng Lou <chenglou92@gmail.com>
Christian Roman <chroman16@gmail.com>
Christoph Pojer <cpojer@fb.com>
Clay Allsopp <clay.allsopp@gmail.com>
Connor McSheffrey <connor.mcsheffrey@gmail.com>
Dan Schafer <dschafer@fb.com>
@@ -15,9 +19,13 @@ Daniel Miladinov <dmiladinov@wingspan.com>
Danny Ben-David <dannybd@fb.com>
David Hu <davidhu91@gmail.com>
Eric Clemmons <eric@smarterspam.com>
Fabio M. Costa <fabiomcosta@gmail.com>
Felix Kling <fkling@fb.com>
Greg Roodt <groodt@gmail.com>
Guido Bouman <m@guido.vc>
Harry Hull <harry.hull1@gmail.com>
Hugo Jobling <me@thisishugo.com>
Ian Obermiller <iano@fb.com>
Isaac Salier-Hellendag <isaac@fb.com>
Jakub Malinowski <jakubmal@gmail.com>
James Ide <ide@fb.com>
@@ -25,14 +33,19 @@ Jamie Wong <jamie.lf.wong@gmail.com>
Jan Kassens <jkassens@fb.com>
Jeff Morrison <jeff@anafx.com>
Jeffrey Lin <lin.jeffrey@gmail.com>
John Watson <jwatson@fb.com>
Jordan Walke <jordojw@gmail.com>
Josh Duck <josh@fb.com>
Keito Uchiyama <keito@fb.com>
Kunal Mehta <k.mehta@berkeley.edu>
Laurence Rowe <l@lrowe.co.uk>
Levi McCallum <levi@levimccallum.com>
Mark Richardson <echo@fb.com>
Marshall Roch <mroch@fb.com>
Martin Konicek <mkonicek@fb.com>
Mathieu M-Gosselin <mathieumg@gmail.com>
Matti Nelimarkka <matti.nelimarkka@hiit.fi>
Mouad Debbar <mdebbar@fb.com>
Nick Gavalas <njg57@cornell.edu>
Owen Coutts <owenc@fb.com>
Paul OShannessy <paul@oshannessy.com>
@@ -40,9 +53,14 @@ Paul Seiffert <paul.seiffert@gmail.com>
Paul Shen <paul@mnml0.com>
Pete Hunt <floydophone@gmail.com>
Peter Cottle <pcottle@fb.com>
Pieter Vanderwerff <pieter@heyday.co.nz>
Sander Spies <sandermail@gmail.com>
Sean Kinsey <oyvind@fb.com>
Sebastian Markbåge <sebastian@calyptus.eu>
Simon Højberg <r.hackr@gmail.com>
Stoyan Stefanov <ssttoo@ymail.com>
Sundeep Malladi <sundeep.malladi@gmail.com>
Thomas Aylott <aylott@fb.com>
Timothy Yung <yungsters@gmail.com>
Vjeux <vjeuxx@gmail.com>
Zach Bruggeman <zbruggeman@me.com>

View File

@@ -1,3 +1,87 @@
## 0.8.0 (December 19, 2013)
### React
* Added support for more attributes:
* `rows` & `cols` for `<textarea>`
* `defer` & `async` for `<script>`
* `loop` for `<audio>` & `<video>`
* `autoCorrect` for form fields (a non-standard attribute only supported by mobile WebKit)
* Improved error messages
* Fixed Selection events in IE11
* Added `onContextMenu` events
### React with Addons
* Fixed bugs with TransitionGroup when children were undefined
* Added support for `onTransition`
### react-tools
* Upgraded `jstransform` and `esprima-fb`
### JSXTransformer
* Added support for use in IE8
* Upgraded browserify, which reduced file size by ~65KB (16KB gzipped)
## 0.5.2, 0.4.2 (December 18, 2013)
### React
* Fixed a potential XSS vulnerability when using user content as a `key`: [CVE-2013-7035](https://groups.google.com/forum/#!topic/reactjs/OIqxlB2aGfU)
## 0.5.1 (October 29, 2013)
### React
* Fixed bug with `<input type="range">` and selection events.
* Fixed bug with selection and focus.
* Made it possible to unmount components from the document root.
* Fixed bug for `disabled` attribute handling on non-`<input>` elements.
### React with Addons
* Fixed bug with transition and animation event detection.
## 0.5.0 (October 16, 2013)
### React
* Memory usage improvements - reduced allocations in core which will help with GC pauses
* Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
* Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
* Support for Selection events.
* Support for [Composition events](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
* Support for additional DOM properties (`charSet`, `content`, `form`, `httpEquiv`, `rowSpan`, `autoCapitalize`).
* Support for additional SVG properties (`rx`, `ry`).
* Support for using `getInitialState` and `getDefaultProps` in mixins.
* Support mounting into iframes.
* Bug fixes for controlled form components.
* Bug fixes for SVG element creation.
* Added `React.version`.
* Added `React.isValidClass` - Used to determine if a value is a valid component constructor.
* Removed `React.autoBind` - This was deprecated in v0.4 and now properly removed.
* Renamed `React.unmountAndReleaseReactRootNode` to `React.unmountComponentAtNode`.
* Began laying down work for refined performance analysis.
* Better support for server-side rendering - [react-page](https://github.com/facebook/react-page) has helped improve the stability for server-side rendering.
* Made it possible to use React in environments enforcing a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy). This also makes it possible to use React to build Chrome extensions.
### React with Addons (New!)
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](http://facebook.github.io/react/docs/addons.html).
### JSX
* No longer transform `class` to `className` as part of the transform! This is a breaking change - if you were using `class`, you *must* change this to `className` or your components will be visually broken.
* Added warnings to the in-browser transformer to make it clear it is not intended for production use.
* Improved compatibility for Windows
* Improved support for maintaining line numbers when transforming.
## 0.4.1 (July 26, 2013)
### React

View File

@@ -8,6 +8,7 @@ var populistTask = require('./grunt/tasks/populist');
var phantomTask = require('./grunt/tasks/phantom');
var npmTask = require('./grunt/tasks/npm');
var releaseTasks = require('./grunt/tasks/release');
var npmReactTasks = require('./grunt/tasks/npm-react');
module.exports = function(grunt) {
@@ -52,17 +53,33 @@ module.exports = function(grunt) {
grunt.registerMultiTask('npm', npmTask);
grunt.registerTask('npm-react:release', npmReactTasks.buildRelease);
// Check that the version we're exporting is the same one we expect in the
// package. This is not an ideal way to do this, but makes sure that we keep
// them in sync.
var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;
grunt.registerTask('version-check', function() {
var version = reactVersionExp.exec(
var reactVersion = reactVersionExp.exec(
grunt.file.read('./build/modules/React.js')
)[1];
var expectedVersion = grunt.config.data.pkg.version;
if (version !== expectedVersion) {
grunt.log.error('Versions do not match. Expected %s, saw %s', expectedVersion, version);
var npmReactVersion = grunt.file.readJSON('./npm-react/package.json').version;
var reactToolsVersion = grunt.config.data.pkg.version;
if (reactVersion !== reactToolsVersion) {
grunt.log.error(
'React version does not match react-tools version. Expected %s, saw %s',
reactToolsVersion,
reactVersion
);
return false;
}
if (npmReactVersion !== reactToolsVersion) {
grunt.log.error(
'npm-react version does not match react-tools veersion. Expected %s, saw %s',
reactToolsVersion,
npmReactVersion
);
return false;
}
});
@@ -79,6 +96,7 @@ module.exports = function(grunt) {
'populist:jasmine',
'populist:test'
]);
grunt.registerTask('build:npm-react', ['version-check', 'jsx:release', 'npm-react:release']);
grunt.registerTask('test', ['build:test', 'build:basic', 'phantom:run']);
grunt.registerTask('npm:test', ['build', 'npm:pack']);
@@ -94,6 +112,7 @@ module.exports = function(grunt) {
'jsx:release',
'browserify:min',
'browserify:addonsMin',
'npm-react:release',
'copy:react_docs',
'compare_size'
]);

View File

@@ -2,21 +2,25 @@
React is a JavaScript library for building user interfaces.
* **Declarative:** React uses a declarative paradigm that makes it easier to reason about your application.
* **Efficient:** React computes the minimal set of changes necessary to keep your DOM up-to-date.
* **Flexible:** React works with the libraries and frameworks that you already know.
* **Just the UI:** Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it's easy to try it out on a small feature in an existing project.
* **Virtual DOM:** React uses a *virtual DOM* diff implementation for ultra-high performance. It can also render on the server using Node.js — no heavy browser DOM required.
* **Data flow:** React implements one-way reactive data flow which reduces boilerplate and is easier to reason about than traditional data binding.
[Learn how to use React in your own project.](http://facebook.github.io/react/docs/getting-started.html)
## The `react` npm package has recently changed!
If you're looking for jeffbski's [React.js](https://github.com/jeffbski/react) project, it's now in `npm` as `reactjs` rather than `react`.
## Examples
We have several examples [on the website](http://facebook.github.io/react). Here is the first one to get you started:
We have several examples [on the website](http://facebook.github.io/react/). Here is the first one to get you started:
```js
/** @jsx React.DOM */
var HelloMessage = React.createClass({
render: function() {
return <div>{'Hello ' + this.props.name}</div>;
return <div>Hello {this.props.name}</div>;
}
});
@@ -36,12 +40,12 @@ The fastest way to get started is to serve JavaScript from the CDN (also availab
```html
<!-- The core React library -->
<script src="http://fb.me/react-0.4.1.js"></script>
<script src="http://fb.me/react-0.8.0.js"></script>
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<script src="http://fb.me/JSXTransformer-0.4.1.js"></script>
<script src="http://fb.me/JSXTransformer-0.8.0.js"></script>
```
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.4.1.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.8.0.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
If you'd like to use [bower](http://bower.io), it's as easy as:
@@ -51,7 +55,7 @@ bower install --save react
## Contribute
The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too :) Any feedback you have about using React would be greatly appreciated.
The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too. :) Any feedback you have about using React would be greatly appreciated.
### Building Your Copy of React
@@ -81,12 +85,10 @@ At this point, you should now have a `build/` directory populated with everythin
We use grunt to automate many tasks. Run `grunt -h` to see a mostly complete listing. The important ones to know:
```sh
# Create test build & run tests with PhantomJS
# Build and run tests with PhantomJS
grunt test
# Lint the core library code with JSHint
# Lint the code with JSHint
grunt lint
# Lint package code
grunt lint:package
# Wipe out build directory
grunt clean
```

View File

@@ -3,7 +3,7 @@ source 'https://rubygems.org'
gem 'rake'
# jekyll, which builds it all
gem 'jekyll', '~>1.0'
gem 'jekyll', '~>1.3.0'
# JSON
gem 'json'

View File

@@ -4,40 +4,47 @@ GEM
classifier (1.3.3)
fast-stemmer (>= 1.0.0)
colorator (0.1)
commander (4.1.3)
commander (4.1.5)
highline (~> 1.6.11)
directory_watcher (1.4.1)
fast-stemmer (1.0.2)
highline (1.6.19)
jekyll (1.0.2)
ffi (1.9.3)
highline (1.6.20)
jekyll (1.3.0)
classifier (~> 1.3)
colorator (~> 0.1)
commander (~> 4.1.3)
directory_watcher (~> 1.4.1)
kramdown (~> 1.0.2)
liquid (~> 2.3)
maruku (~> 0.5)
liquid (~> 2.5.2)
listen (~> 1.3)
maruku (~> 0.6.0)
pygments.rb (~> 0.5.0)
safe_yaml (~> 0.7.0)
json (1.8.0)
kramdown (1.0.2)
liquid (2.5.0)
redcarpet (~> 2.3.0)
safe_yaml (~> 0.9.7)
json (1.8.1)
liquid (2.5.4)
listen (1.3.1)
rb-fsevent (>= 0.9.3)
rb-inotify (>= 0.9)
rb-kqueue (>= 0.2)
maruku (0.6.1)
syntax (>= 1.0.0)
mini_portile (0.5.1)
mini_portile (0.5.2)
nokogiri (1.6.0)
mini_portile (~> 0.5.0)
posix-spawn (0.3.6)
pygments.rb (0.5.0)
pygments.rb (0.5.4)
posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.1.0)
rake (10.0.4)
rake (10.1.0)
rb-fsevent (0.9.3)
redcarpet (2.2.2)
safe_yaml (0.7.1)
rb-inotify (0.9.2)
ffi (>= 0.5.0)
rb-kqueue (0.2.0)
ffi (>= 0.5.0)
redcarpet (2.3.0)
safe_yaml (0.9.7)
sanitize (2.0.6)
nokogiri (>= 1.4.4)
sass (3.2.9)
sass (3.2.12)
syntax (1.0.0)
yajl-ruby (1.1.0)
@@ -45,7 +52,7 @@ PLATFORMS
ruby
DEPENDENCIES
jekyll (~> 1.0)
jekyll (~> 1.3.0)
json
rake
rb-fsevent

View File

@@ -21,6 +21,7 @@ Once you have RubyGems and installed Bundler (via `gem install bundler`), use it
```sh
$ cd react/docs
$ bundle install # Might need sudo.
$ npm install # Might need sudo.
```
### Instructions

View File

@@ -13,59 +13,9 @@ redcarpet:
pygments: true
name: React
markdown: redcarpet
react_version: 0.4.0
react_version: 0.8.0
description: A JavaScript library for building user interfaces
relative_permalinks: true
paginate: 5
paginate_path: /blog/page:num
nav_docs_sections:
- title: Quick Start
items:
- id: getting-started
title: Getting Started
- id: tutorial
title: Tutorial
- title: Guides
items:
- id: why-react
title: Why React?
- id: displaying-data
title: Displaying Data
subitems:
- id: jsx-in-depth
title: JSX in Depth
- id: jsx-gotchas
title: JSX Gotchas
- id: interactivity-and-dynamic-uis
title: Interactivity and Dynamic UIs
- id: multiple-components
title: Multiple Components
- id: reusable-components
title: Reusable Components
- id: forms
title: Forms
- id: working-with-the-browser
title: Working With the Browser
subitems:
- id: more-about-refs
title: More About Refs
- id: tooling-integration
title: Tooling Integration
- id: addons
title: Add-ons
- id: examples
title: Examples
- title: Reference
items:
- id: top-level-api
title: Top-Level API
- id: component-api
title: Component API
- id: component-specs
title: Component Specs and Lifecycle
- id: tags-and-attributes
title: Supported Tags and Attributes
- id: events
title: Event System
- id: dom-differences
title: DOM Differences
paginate_path: /blog/page:num/
timezone: America/Los_Angeles

View File

@@ -15,6 +15,7 @@ $contentPadding: 20px;
$columnWidth: 280px;
$columnGutter: 40px;
$twoColumnWidth: 2 * $columnWidth + $columnGutter;
$navHeight: 50px;
@@ -42,7 +43,7 @@ html {
.container {
padding-top: 50px;
padding-top: $navHeight;
min-width: $contentWidth + (2 * $contentPadding);
}
@@ -73,6 +74,23 @@ li {
margin-left: 20px;
}
// Make header navigation linkable and on the screen. Used in documentation and
// blog posts.
h1, h2, h3, h4, h5, h6 {
.anchor {
margin-top: -$navHeight;
position: absolute;
}
&:hover .hash-link {
display: inline;
}
}
.hash-link {
color: $mediumTextColor;
display: none;
}
// Main Nav
.nav-main {
@@ -81,7 +99,7 @@ li {
color: $lightTextColor;
position: fixed;
top: 0;
height: 50px;
height: $navHeight;
box-shadow: 0 0 5px rgba(0, 0, 0, .5);
width: 100%;
z-index: 100;
@@ -103,9 +121,9 @@ li {
padding: 0 8px;
text-transform: uppercase;
letter-spacing: 1px;
line-height: 50px;
line-height: $navHeight;
display: inline-block;
height: 50px;
height: $navHeight;
color: $mediumTextColor;
&:hover {
@@ -123,7 +141,7 @@ li {
.nav-home {
color: #00d8ff;
font-size: 24px;
line-height: 50px;
line-height: $navHeight;
}
.nav-logo {
@@ -272,7 +290,7 @@ li {
.marketing-col {
float: left;
margin-right: 40px;
margin-left: 40px;
width: $columnWidth;
h3 {
@@ -286,8 +304,8 @@ li {
}
}
.marketing-col:last-child {
margin-right: 0;
.marketing-col:first-child {
margin-left: 0;
}
#examples h3, .home-presentation h3 {
@@ -369,6 +387,8 @@ section.black content {
*/
.blogContent {
@include clearfix;
padding-top: 20px;
blockquote {
@@ -391,6 +411,7 @@ section.black content {
font-size: 24px;
}
// H2s form documentation topic dividers. Extra space helps.
h2 {
margin-top: 30px;
@@ -398,7 +419,7 @@ section.black content {
padding-top: 20px;
// Make a notice box out of blockquotes in the documetation:
// Make a notice box out of blockquotes in the documentation:
blockquote {
padding: 15px 30px 15px 15px;
margin: 20px 0;
@@ -407,7 +428,7 @@ section.black content {
h4 {
margin-top: 0;
}
p:last-child {
p {
margin-bottom: 0;
}
// Treat first child as the title - promote to H4.
@@ -438,13 +459,19 @@ section.black content {
}
.playgroundPreview {
padding: 14px;
padding: 0;
width: 600px;
pre {
@include code-typography;
}
}
.playgroundError {
// The compiler view kills padding in order to render the CodeMirror code
// more nicely. For the error view, put a padding back
padding: 15px 20px;
}
}
/* Button */
@@ -539,7 +566,7 @@ figure {
margin-top: 60px;
}
/* Code Mirror */
/* CodeMirror */
div.CodeMirror pre, div.CodeMirror-linenumber, code {
@include code-typography;
@@ -553,6 +580,11 @@ div.CodeMirror-linenumber:after {
border: none;
}
/* hide the cursor. Mostly used when code's in plain JS */
.CodeMirror-readonly div.CodeMirror-cursor {
visibility: hidden;
}
small code,
li code,
p code {
@@ -569,23 +601,28 @@ p code {
@include clearfix;
}
.playground::before {
.playground-tab {
border-bottom: none !important;
border-radius: 3px 3px 0 0;
padding: 3px 7px;
padding: 6px 8px;
font-size: 12px;
font-weight: bold;
color: #c2c0bc;
background-color: #f1ede4;
content: 'Live editor';
display: inline-block;
cursor: pointer;
}
.playground::before,
.playgroundCode,
.playground-tab,
.playgroundPreview {
border: 1px solid rgba(16,16,16,0.1);
}
.playground-tab-active {
color: $darkestColor;
}
.playgroundCode {
border-radius: 0 3px 3px 3px;
float: left;
@@ -601,6 +638,11 @@ p code {
width: $columnWidth;
}
.playgroundError {
color: darken($primary, 5%);
font-size: 15px;
}
.MarkdownEditor textarea {
width: 100%;
height: 100px
@@ -615,7 +657,7 @@ p code {
padding-left: 9px;
}
/* Codemirror doesn't support <jsx> syntax. Instead of highlighting it
/* CodeMirror doesn't support <jsx> syntax. Instead of highlighting it
as error, just ignore it */
.highlight .javascript .err {
background-color: transparent;
@@ -702,3 +744,8 @@ p code {
float: right;
}
}
// Twitter embeds. Need to !important because they inline margin on the iframe.
div[data-twttr-id] iframe {
margin: 10px auto !important;
}

67
docs/_data/nav_docs.yml Normal file
View File

@@ -0,0 +1,67 @@
- title: Quick Start
items:
- id: getting-started
title: Getting Started
- id: tutorial
title: Tutorial
- id: videos
title: Videos
- id: complementary-tools
title: Complementary tools
- id: example-apps
title: Example apps
- title: Guides
items:
- id: why-react
title: Why React?
- id: displaying-data
title: Displaying Data
subitems:
- id: jsx-in-depth
title: JSX in Depth
- id: jsx-gotchas
title: JSX Gotchas
- id: interactivity-and-dynamic-uis
title: Interactivity and Dynamic UIs
- id: multiple-components
title: Multiple Components
- id: reusable-components
title: Reusable Components
- id: forms
title: Forms
- id: working-with-the-browser
title: Working With the Browser
subitems:
- id: more-about-refs
title: More About Refs
- id: tooling-integration
title: Tooling Integration
- id: addons
title: Add-Ons
subitems:
- id: animation
title: Animation
- id: two-way-binding-helpers
title: Two-Way Binding Helpers
- id: class-name-manipulation
title: Class Name Manipulation
- id: examples
title: Examples
- title: Reference
items:
- id: top-level-api
title: Top-Level API
- id: component-api
title: Component API
- id: component-specs
title: Component Specs and Lifecycle
- id: tags-and-attributes
title: Supported Tags and Attributes
- id: events
title: Event System
- id: dom-differences
title: DOM Differences
- id: special-non-dom-attributes
title: Special Non-DOM attributes
- id: reconciliation
title: Reconciliation

32
docs/_data/nav_tips.yml Normal file
View File

@@ -0,0 +1,32 @@
- title: Tips
items:
- id: introduction
title: Introduction
- id: inline-styles
title: Inline Styles
- id: if-else-in-JSX
title: If-Else in JSX
- id: self-closing-tag
title: Self-Closing Tag
- id: maximum-number-of-jsx-root-nodes
title: Maximum Number of JSX Root Nodes
- id: style-props-value-px
title: Shorthand for Specifying Pixel Values in style props
- id: children-props-type
title: Type of the Children props
- id: controlled-input-null-value
title: Value of null for Controlled Input
- id: componentWillReceiveProps-not-triggered-after-mounting
title: componentWillReceiveProps Not Triggered After Mounting
- id: props-in-getInitialState-as-anti-pattern
title: Props in getInitialState Is an Anti-Pattern
- id: dom-event-listeners
title: DOM Event Listeners in a Component
- id: initial-ajax
title: Load Initial Data via AJAX
- id: false-in-jsx
title: False in JSX
- id: communicate-between-components
title: Communicate Between Components
- id: expose-component-functions
title: Expose Component Functions

View File

@@ -1,5 +1,6 @@
<div class="nav-docs">
{% for section in site.nav_docs_sections %}
<!-- Docs Nav -->
{% for section in site.data.nav_docs %}
<div class="nav-docs-section">
<h3>{{ section.title }}</h3>
<ul>
@@ -24,4 +25,18 @@
</ul>
</div>
{% endfor %}
<!-- Tips Nav -->
{% for section in site.data.nav_tips %}
<div class="nav-docs-section">
<h3>{{ section.title }}</h3>
<ul>
{% for item in section.items %}
<li>
<a href="/react/tips/{{ item.id }}.html"{% if page.id == item.id %} class="active"{% endif %}>{{ item.title }}</a>
</li>
{% endfor %}
</ul>
</div>
{% endfor %}
</div>

2
docs/_js/es5-sham.min.js vendored Normal file

File diff suppressed because one or more lines are too long

2
docs/_js/es5-shim.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -6,7 +6,7 @@ var HELLO_COMPONENT = "\
/** @jsx React.DOM */\n\
var HelloMessage = React.createClass({\n\
render: function() {\n\
return <div>{'Hello ' + this.props.name}</div>;\n\
return <div>Hello {this.props.name}</div>;\n\
}\n\
});\n\
\n\

View File

@@ -3,6 +3,7 @@
*/
var TIMER_COMPONENT = "\
/** @jsx React.DOM */\n\
var Timer = React.createClass({\n\
getInitialState: function() {\n\
return {secondsElapsed: 0};\n\
@@ -17,13 +18,13 @@ var Timer = React.createClass({\n\
clearInterval(this.interval);\n\
},\n\
render: function() {\n\
return React.DOM.div({},\n\
'Seconds Elapsed: ' + this.state.secondsElapsed\n\
return (\n\
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>\n\
);\n\
}\n\
});\n\
\n\
React.renderComponent(Timer({}), mountNode);\
React.renderComponent(<Timer />, mountNode);\
";
React.renderComponent(

482
docs/_js/html-jsx-lib.js Normal file
View File

@@ -0,0 +1,482 @@
/**
* Copyright 2013 Facebook, Inc.
*
* 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.
*/
/**
* This is a very simple HTML to JSX converter. It turns out that browsers
* have good HTML parsers (who would have thought?) so we utilise this by
* inserting the HTML into a temporary DOM node, and then do a breadth-first
* traversal of the resulting DOM tree.
*/
;(function(global) {
'use strict';
// https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType
var NODE_TYPE = {
ELEMENT: 1,
TEXT: 3,
COMMENT: 8
};
var ATTRIBUTE_MAPPING = {
'for': 'htmlFor',
'class': 'className'
};
/**
* Repeats a string a certain number of times.
* Also: the future is bright and consists of native string repetition:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
*
* @param {string} string String to repeat
* @param {number} times Number of times to repeat string. Integer.
* @see http://jsperf.com/string-repeater/2
*/
function repeatString(string, times) {
if (times === 1) {
return string;
}
if (times < 0) { throw new Error(); }
var repeated = '';
while (times) {
if (times & 1) {
repeated += string;
}
if (times >>= 1) {
string += string;
}
}
return repeated;
}
/**
* Determine if the string ends with the specified substring.
*
* @param {string} haystack String to search in
* @param {string} needle String to search for
* @return {boolean}
*/
function endsWith(haystack, needle) {
return haystack.slice(-needle.length) === needle;
}
/**
* Trim the specified substring off the string. If the string does not end
* with the specified substring, this is a no-op.
*
* @param {string} haystack String to search in
* @param {string} needle String to search for
* @return {string}
*/
function trimEnd(haystack, needle) {
return endsWith(haystack, needle)
? haystack.slice(0, -needle.length)
: haystack;
}
/**
* Convert a hyphenated string to camelCase.
*/
function hyphenToCamelCase(string) {
return string.replace(/-(.)/g, function(match, chr) {
return chr.toUpperCase();
});
}
/**
* Determines if the specified string consists entirely of whitespace.
*/
function isEmpty(string) {
return !/[^\s]/.test(string);
}
/**
* Determines if the specified string consists entirely of numeric characters.
*/
function isNumeric(input) {
return input !== undefined
&& input !== null
&& (typeof input === 'number' || parseInt(input, 10) == input);
}
var HTMLtoJSX = function(config) {
this.config = config || {};
if (this.config.createClass === undefined) {
this.config.createClass = true;
}
if (!this.config.indent) {
this.config.indent = ' ';
}
if (!this.config.outputClassName) {
this.config.outputClassName = 'NewComponent';
}
};
HTMLtoJSX.prototype = {
/**
* Reset the internal state of the converter
*/
reset: function() {
this.output = '';
this.level = 0;
},
/**
* Main entry point to the converter. Given the specified HTML, returns a
* JSX object representing it.
* @param {string} html HTML to convert
* @return {string} JSX
*/
convert: function(html) {
this.reset();
// It turns out browsers have good HTML parsers (imagine that).
// Let's take advantage of it.
var containerEl = document.createElement('div');
containerEl.innerHTML = '\n' + this._cleanInput(html) + '\n';
if (this.config.createClass) {
if (this.config.outputClassName) {
this.output = 'var ' + this.config.outputClassName + ' = React.createClass({\n';
} else {
this.output = 'React.createClass({\n';
}
this.output += this.config.indent + 'render: function() {' + "\n";
this.output += this.config.indent + this.config.indent + 'return (\n';
}
if (this._onlyOneTopLevel(containerEl)) {
// Only one top-level element, the component can return it directly
// No need to actually visit the container element
this._traverse(containerEl);
} else {
// More than one top-level element, need to wrap the whole thing in a
// container.
this.output += this.config.indent + this.config.indent + this.config.indent;
this.level++;
this._visit(containerEl);
}
this.output = this.output.trim() + '\n';
if (this.config.createClass) {
this.output += this.config.indent + this.config.indent + ');\n';
this.output += this.config.indent + '}\n';
this.output += '});';
}
return this.output;
},
/**
* Cleans up the specified HTML so it's in a format acceptable for
* converting.
*
* @param {string} html HTML to clean
* @return {string} Cleaned HTML
*/
_cleanInput: function(html) {
// Remove unnecessary whitespace
html = html.trim();
// Ugly method to strip script tags. They can wreak havoc on the DOM nodes
// so let's not even put them in the DOM.
html = html.replace(/<script(.*?)<\/script>/g, '');
return html;
},
/**
* Determines if there's only one top-level node in the DOM tree. That is,
* all the HTML is wrapped by a single HTML tag.
*
* @param {DOMElement} containerEl Container element
* @return {boolean}
*/
_onlyOneTopLevel: function(containerEl) {
// Only a single child element
if (
containerEl.childNodes.length === 1
&& containerEl.childNodes[0].nodeType === NODE_TYPE.ELEMENT
) {
return true;
}
// Only one element, and all other children are whitespace
var foundElement = false;
for (var i = 0, count = containerEl.childNodes.length; i < count; i++) {
var child = containerEl.childNodes[i];
if (child.nodeType === NODE_TYPE.ELEMENT) {
if (foundElement) {
// Encountered an element after already encountering another one
// Therefore, more than one element at root level
return false;
} else {
foundElement = true;
}
} else if (child.nodeType === NODE_TYPE.TEXT && !isEmpty(child.textContent)) {
// Contains text content
return false;
}
}
return true;
},
/**
* Gets a newline followed by the correct indentation for the current
* nesting level
*
* @return {string}
*/
_getIndentedNewline: function() {
return '\n' + repeatString(this.config.indent, this.level + 2);
},
/**
* Handles processing the specified node
*
* @param {Node} node
*/
_visit: function(node) {
this._beginVisit(node);
this._traverse(node);
this._endVisit(node);
},
/**
* Traverses all the children of the specified node
*
* @param {Node} node
*/
_traverse: function(node) {
this.level++;
for (var i = 0, count = node.childNodes.length; i < count; i++) {
this._visit(node.childNodes[i]);
}
this.level--;
},
/**
* Handle pre-visit behaviour for the specified node.
*
* @param {Node} node
*/
_beginVisit: function(node) {
switch (node.nodeType) {
case NODE_TYPE.ELEMENT:
this._beginVisitElement(node);
break;
case NODE_TYPE.TEXT:
this._visitText(node);
break;
case NODE_TYPE.COMMENT:
this._visitComment(node);
break;
default:
console.warn('Unrecognised node type: ' + node.nodeType);
}
},
/**
* Handles post-visit behaviour for the specified node.
*
* @param {Node} node
*/
_endVisit: function(node) {
switch (node.nodeType) {
case NODE_TYPE.ELEMENT:
this._endVisitElement(node);
break;
// No ending tags required for these types
case NODE_TYPE.TEXT:
case NODE_TYPE.COMMENT:
break;
}
},
/**
* Handles pre-visit behaviour for the specified element node
*
* @param {DOMElement} node
*/
_beginVisitElement: function(node) {
var tagName = node.tagName.toLowerCase();
var attributes = [];
for (var i = 0, count = node.attributes.length; i < count; i++) {
attributes.push(this._getElementAttribute(node, node.attributes[i]));
}
this.output += '<' + tagName;
if (attributes.length > 0) {
this.output += ' ' + attributes.join(' ');
}
if (node.firstChild) {
this.output += '>';
}
},
/**
* Handles post-visit behaviour for the specified element node
*
* @param {Node} node
*/
_endVisitElement: function(node) {
// De-indent a bit
// TODO: It's inefficient to do it this way :/
this.output = trimEnd(this.output, this.config.indent);
if (node.firstChild) {
this.output += '</' + node.tagName.toLowerCase() + '>';
} else {
this.output += ' />';
}
},
/**
* Handles processing of the specified text node
*
* @param {TextNode} node
*/
_visitText: function(node) {
var text = node.textContent;
// If there's a newline in the text, adjust the indent level
if (text.indexOf('\n') > -1) {
text = node.textContent.replace(/\n\s*/g, this._getIndentedNewline());
}
this.output += text;
},
/**
* Handles processing of the specified text node
*
* @param {Text} node
*/
_visitComment: function(node) {
// Do not render the comment
// Since we remove comments, we also need to remove the next line break so we
// don't end up with extra whitespace after every comment
//if (node.nextSibling && node.nextSibling.nodeType === NODE_TYPE.TEXT) {
// node.nextSibling.textContent = node.nextSibling.textContent.replace(/\n\s*/, '');
//}
this.output += '{/*' + node.textContent.replace('*/', '* /') + '*/}';
},
/**
* Gets a JSX formatted version of the specified attribute from the node
*
* @param {DOMElement} node
* @param {object} attribute
* @return {string}
*/
_getElementAttribute: function(node, attribute) {
switch (attribute.name) {
case 'style':
return this._getStyleAttribute(attribute.value);
default:
var name = ATTRIBUTE_MAPPING[attribute.name] || attribute.name;
var result = name + '=';
// Numeric values should be output as {123} not "123"
if (isNumeric(attribute.value)) {
result += '{' + attribute.value + '}';
} else {
result += '"' + attribute.value.replace('"', '&quot;') + '"';
}
return result;
}
},
/**
* Gets a JSX formatted version of the specified element styles
*
* @param {string} styles
* @return {string}
*/
_getStyleAttribute: function(styles) {
var jsxStyles = new StyleParser(styles).toJSXString();
return 'style={{' + jsxStyles + '}}';
}
};
/**
* Handles parsing of inline styles
*
* @param {string} rawStyle Raw style attribute
* @constructor
*/
var StyleParser = function(rawStyle) {
this.parse(rawStyle);
};
StyleParser.prototype = {
/**
* Parse the specified inline style attribute value
* @param {string} rawStyle Raw style attribute
*/
parse: function(rawStyle) {
this.styles = {};
rawStyle.split(';').forEach(function(style) {
style = style.trim();
var firstColon = style.indexOf(':');
var key = style.substr(0, firstColon);
var value = style.substr(firstColon + 1).trim();
if (key !== '') {
this.styles[key] = value;
}
}, this);
},
/**
* Convert the style information represented by this parser into a JSX
* string
*
* @return {string}
*/
toJSXString: function() {
var output = [];
for (var key in this.styles) {
if (!this.styles.hasOwnProperty(key)) {
continue;
}
output.push(this.toJSXKey(key) + ': ' + this.toJSXValue(this.styles[key]));
}
return output.join(', ');
},
/**
* Convert the CSS style key to a JSX style key
*
* @param {string} key CSS style key
* @return {string} JSX style key
*/
toJSXKey: function(key) {
return hyphenToCamelCase(key);
},
/**
* Convert the CSS style value to a JSX style value
*
* @param {string} value CSS style value
* @return {string} JSX style value
*/
toJSXValue: function(value) {
if (isNumeric(value)) {
// If numeric, no quotes
return value;
} else if (endsWith(value, 'px')) {
// "500px" -> 500
return trimEnd(value, 'px');
} else {
// Proably a string, wrap it in quotes
return '\'' + value.replace(/'/g, '"') + '\'';
}
}
};
// Expose public API
global.HTMLtoJSX = HTMLtoJSX;
}(window));

89
docs/_js/html-jsx.js Normal file
View File

@@ -0,0 +1,89 @@
/**
* Copyright 2013 Facebook, Inc.
*
* 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 is a web interface for the HTML to JSX converter contained in
* `html-jsx-lib.js`.
*/
;(function() {
var HELLO_COMPONENT = "\
<!-- Hello world -->\n\
<div class=\"awesome\" style=\"border: 1px solid red\">\n\
<label for=\"name\">Enter your name: </label>\n\
<input type=\"text\" id=\"name\" />\n\
</div>\n\
<p>Enter your HTML here</p>\
";
var HTMLtoJSXComponent = React.createClass({
getInitialState: function() {
return {
outputClassName: 'NewComponent',
createClass: true
};
},
onReactClassNameChange: function(evt) {
this.setState({ outputClassName: evt.target.value });
},
onCreateClassChange: function(evt) {
this.setState({ createClass: evt.target.checked });
},
setInput: function(input) {
this.setState({ input: input });
this.convertToJsx();
},
convertToJSX: function(input) {
var converter = new HTMLtoJSX({
outputClassName: this.state.outputClassName,
createClass: this.state.createClass
});
return converter.convert(input);
},
render: function() {
return (
<div>
<div id="options">
<label>
<input
type="checkbox"
checked={this.state.createClass}
onChange={this.onCreateClassChange} />
Create class
</label>
<label style={{display: this.state.createClass ? '' : 'none'}}>
·
Class name:
<input
type="text"
value={this.state.outputClassName}
onChange={this.onReactClassNameChange} />
</label>
</div>
<ReactPlayground
codeText={HELLO_COMPONENT}
renderCode={true}
transformer={this.convertToJSX}
/>
</div>
);
}
});
React.renderComponent(<HTMLtoJSXComponent />, document.getElementById('jsxCompiler'));
}());

8
docs/_js/html5shiv.min.js vendored Normal file
View File

@@ -0,0 +1,8 @@
/*
HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>";
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment();
for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);

View File

@@ -6,14 +6,21 @@ var HELLO_COMPONENT = "\
/** @jsx React.DOM */\n\
var HelloMessage = React.createClass({\n\
render: function() {\n\
return <div>{'Hello ' + this.props.name}</div>;\n\
return <div>Hello {this.props.name}</div>;\n\
}\n\
});\n\
\n\
React.renderComponent(<HelloMessage name=\"John\" />, mountNode);\
";
var transformer = function(code) {
return JSXTransformer.transform(code).code;
}
React.renderComponent(
<ReactPlayground codeText={HELLO_COMPONENT} renderCode={true} />,
<ReactPlayground
codeText={HELLO_COMPONENT}
renderCode={true}
transformer={transformer}
/>,
document.getElementById('jsxCompiler')
);

View File

@@ -14,25 +14,33 @@ var IS_MOBILE = (
);
var CodeMirrorEditor = React.createClass({
componentDidMount: function(root) {
if (IS_MOBILE) {
return;
}
componentDidMount: function() {
if (IS_MOBILE) return;
this.editor = CodeMirror.fromTextArea(this.refs.editor.getDOMNode(), {
mode: 'javascript',
lineNumbers: false,
lineWrapping: true,
smartIndent: false, // javascript mode does bad things with jsx indents
matchBrackets: true,
theme: 'solarized-light'
theme: 'solarized-light',
readOnly: this.props.readOnly
});
this.editor.on('change', this.onChange);
this.onChange();
this.editor.on('change', this.handleChange);
},
onChange: function() {
if (this.props.onChange) {
var content = this.editor.getValue();
this.props.onChange(content);
componentDidUpdate: function() {
if (this.props.readOnly) {
this.editor.setValue(this.props.codeText);
}
},
handleChange: function() {
if (!this.props.readOnly) {
this.props.onChange && this.props.onChange(this.editor.getValue());
}
},
render: function() {
// wrap in a div to fully contain CodeMirror
var editor;
@@ -44,87 +52,152 @@ var CodeMirrorEditor = React.createClass({
}
return (
<div class={this.props.className}>
<div style={this.props.style} className={this.props.className}>
{editor}
</div>
);
}
});
var selfCleaningTimeout = {
componentDidUpdate: function() {
clearTimeout(this.timeoutID);
},
setTimeout: function() {
clearTimeout(this.timeoutID);
this.timeoutID = setTimeout.apply(null, arguments);
}
};
var ReactPlayground = React.createClass({
MODES: {XJS: 'XJS', JS: 'JS'}, //keyMirror({XJS: true, JS: true}),
mixins: [selfCleaningTimeout],
MODES: {JSX: 'JSX', JS: 'JS'}, //keyMirror({JSX: true, JS: true}),
propTypes: {
codeText: React.PropTypes.string.isRequired,
transformer: React.PropTypes.func,
renderCode: React.PropTypes.bool,
},
getDefaultProps: function() {
return {
transformer: function(code) {
return JSXTransformer.transform(code).code;
}
};
},
getInitialState: function() {
return {mode: this.MODES.XJS, code: this.props.codeText};
return {
mode: this.MODES.JSX,
code: this.props.codeText,
};
},
bindState: function(name) {
return function(value) {
var newState = {};
newState[name] = value;
this.setState(newState);
}.bind(this);
handleCodeChange: function(value) {
this.setState({code: value});
this.executeCode();
},
getDesugaredCode: function() {
return JSXTransformer.transform(this.state.code).code;
handleCodeModeSwitch: function(mode) {
this.setState({mode: mode});
},
compileCode: function() {
return this.props.transformer(this.state.code);
},
render: function() {
var content;
if (this.state.mode === this.MODES.XJS) {
content =
<CodeMirrorEditor
onChange={this.bindState('code')}
class="playgroundStage"
codeText={this.state.code}
/>;
} else if (this.state.mode === this.MODES.JS) {
content =
<div class="playgroundJS playgroundStage">
{this.getDesugaredCode()}
</div>;
}
var isJS = this.state.mode === this.MODES.JS;
var compiledCode = '';
try {
compiledCode = this.compileCode();
} catch (err) {}
var jsContent =
<CodeMirrorEditor
key="js"
className="playgroundStage CodeMirror-readonly"
onChange={this.handleCodeChange}
codeText={compiledCode}
readOnly={true}
/>;
var jsxContent =
<CodeMirrorEditor
key="jsx"
onChange={this.handleCodeChange}
className="playgroundStage"
codeText={this.state.code}
/>;
var JSXTabClassName =
'playground-tab' + (isJS ? '' : ' playground-tab-active');
var JSTabClassName =
'playground-tab' + (isJS ? ' playground-tab-active' : '');
return (
<div class="playground">
<div class="playgroundCode">
{content}
<div className="playground">
<div>
<div
className={JSXTabClassName}
onClick={this.handleCodeModeSwitch.bind(this, this.MODES.JSX)}>
Live JSX Editor
</div>
<div
className={JSTabClassName}
onClick={this.handleCodeModeSwitch.bind(this, this.MODES.JS)}>
Compiled JS
</div>
</div>
<div class="playgroundPreview">
<div className="playgroundCode">
{isJS ? jsContent : jsxContent}
</div>
<div className="playgroundPreview">
<div ref="mount" />
</div>
</div>
);
},
componentDidMount: function() {
this.executeCode();
},
componentDidUpdate: function() {
this.executeCode();
componentWillUpdate: function(nextProps, nextState) {
// execute code only when the state's not being updated by switching tab
// this avoids re-displaying the error, which comes after a certain delay
if (this.state.code !== nextState.code) {
this.executeCode();
}
},
executeCode: function() {
var mountNode = this.refs.mount.getDOMNode();
try {
React.unmountAndReleaseReactRootNode(mountNode);
React.unmountComponentAtNode(mountNode);
} catch (e) { }
try {
var compiledCode = this.compileCode();
if (this.props.renderCode) {
React.renderComponent(
<pre>{this.getDesugaredCode()}</pre>,
<CodeMirrorEditor codeText={compiledCode} readOnly={true} />,
mountNode
);
} else {
eval(this.getDesugaredCode());
eval(compiledCode);
}
} catch (e) {
React.renderComponent(
<div content={e.toString()} class="playgroundError" />,
mountNode
);
} catch (err) {
this.setTimeout(function() {
React.renderComponent(
<div className="playgroundError">{err.toString()}</div>,
mountNode
);
}, 500);
}
}
});

View File

@@ -1,4 +1,5 @@
<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
@@ -15,13 +16,18 @@
<link rel="shortcut icon" href="/react/favicon.ico">
<link rel="alternate" type="application/rss+xml" title="{{ site.name }}" href="{{ site.url }}{{ site.baseurl }}/feed.xml">
<link rel="stylesheet" href="/react/css/react.css">
<link rel="stylesheet" href="/react/css/syntax.css">
<link rel="stylesheet" href="/react/css/codemirror.css">
<link rel="stylesheet" href="/react/css/react.css">
<script type="text/javascript" src="//use.typekit.net/vqa1hcx.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<!--[if lte IE 8]>
<script type="text/javascript" src="/react/js/html5shiv.min.js"></script>
<script type="text/javascript" src="/react/js/es5-shim.min.js"></script>
<script type="text/javascript" src="/react/js/es5-sham.min.js"></script>
<![endif]-->
<script type="text/javascript" src="/react/js/codemirror.js"></script>
<script type="text/javascript" src="/react/js/javascript.js"></script>
<script type="text/javascript" src="/react/js/react.min.js"></script>
@@ -46,7 +52,6 @@
<li><a href="/react/blog/"{% if page.sectionid == 'blog' %} class="active"{% endif %}>blog</a></li>
<li><a href="http://github.com/facebook/react">github</a>
</ul>
<!-- <iframe src="http://ghbtns.com/github&#45;btn.html?user=facebook&#38;repo=react.js&#38;type=fork"allowtransparency="true" frameborder="0" scrolling="0" width="62" height="20"></iframe> -->
</div>
</div>
@@ -70,10 +75,11 @@
<footer class="wrap">
<div class="left">A Facebook &amp; Instagram collaboration.</div>
<div class="right">&copy; 2013 Facebook Inc.</div>
<div class="right">&copy; 2014 Facebook Inc.</div>
</footer>
</div>
<div id="fb-root"></div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

25
docs/_layouts/tips.html Normal file
View File

@@ -0,0 +1,25 @@
---
layout: default
sectionid: tips
---
<section class="content wrap documentationContent">
{% include nav_docs.html %}
<div class="inner-content">
<h1>{{ page.title }}</h1>
<div class="subHeader">{{ page.description }}</div>
{{ content }}
<div class="docs-prevnext">
{% if page.prev %}
<a class="docs-prev" href="/react/tips/{{ page.prev }}">&larr; Prev</a>
{% endif %}
{% if page.next %}
<a class="docs-next" href="/react/tips/{{ page.next }}">Next &rarr;</a>
{% endif %}
</div>
<div class="fb-comments" data-width="650" data-num-posts="10" data-href="{{ site.url }}{{ site.baseurl }}{{ page.url }}"></div>
</div>
</section>

View File

@@ -11,7 +11,7 @@ class Redcarpet::Render::HTML
.gsub(/\s+/, "-")
.gsub(/[^A-Za-z0-9\-_.]/, "")
return "<h#{level} id=\"#{clean_title}\">#{title}</h#{level}>"
return "<h#{level}><a class=\"anchor\" name=\"#{clean_title}\"></a>#{title} <a class=\"hash-link\" href=\"##{clean_title}\">#</a></h#{level}>"
end
end

View File

@@ -31,8 +31,8 @@ to render views, which we see as an advantage over templates for a few reasons:
**no manual string concatenation** and therefore less surface area for XSS
vulnerabilities.
We've also created [JSX](http://facebook.github.io/react/docs/syntax.html), an optional
syntax extension, in case you prefer the readability of HTML to raw JavaScript.
We've also created [JSX](/react/docs/jsx-in-depth.html), an optional syntax
extension, in case you prefer the readability of HTML to raw JavaScript.
## Reactive updates are dead simple.
@@ -81,11 +81,9 @@ some pretty cool things with it:
(including IE8) and automatically use
[event delegation](http://davidwalsh.name/event-delegate).
Head on over to
[facebook.github.io/react](http://facebook.github.io/react) to check
out what we have built. Our documentation is geared towards building
apps with the framework, but if you are interested in the
nuts and bolts
[get in touch](http://facebook.github.io/react/support.html) with us!
Head on over to [facebook.github.io/react](/react) to check out what we have
built. Our documentation is geared towards building apps with the framework,
but if you are interested in the nuts and bolts
[get in touch](/react/support.html) with us!
Thanks for reading!

View File

@@ -0,0 +1,52 @@
---
title: "React v0.5"
layout: post
author: Paul O'Shannessy
---
This release is the result of several months of hard work from members of the team and the community. While there are no groundbreaking changes in core, we've worked hard to improve performance and memory usage. We've also worked hard to make sure we are being consistent in our usage of DOM properties.
The biggest change you'll notice as a developer is that we no longer support `class` in JSX as a way to provide CSS classes. Since this prop was being converted to `className` at the transform step, it caused some confusion when trying to access it in composite components. As a result we decided to make our DOM properties mirror their counterparts in the JS DOM API. There are [a few exceptions](https://github.com/facebook/react/blob/master/src/dom/DefaultDOMPropertyConfig.js#L156) where we deviate slightly in an attempt to be consistent internally.
The other major change in v0.5 is that we've added an additional build - `react-with-addons` - which adds support for some extras that we've been working on including animations and two-way binding. [Read more about these addons in the docs](/react/docs/addons.html).
## Thanks to Our Community
We added *22 new people* to the list of authors since we launched React v0.4.1 nearly 3 months ago. With a total of 48 names in our `AUTHORS` file, that means we've nearly doubled the number of contributors in that time period. We've seen the number of people contributing to discussion on IRC, mailing lists, Stack Overflow, and GitHub continue rising. We've also had people tell us about talks they've given in their local community about React.
It's been awesome to see the things that people are building with React, and we can't wait to see what you come up with next!
## Changelog
### React
* Memory usage improvements - reduced allocations in core which will help with GC pauses
* Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
* Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
* Support for Selection events.
* Support for [Composition events](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
* Support for additional DOM properties (`charSet`, `content`, `form`, `httpEquiv`, `rowSpan`, `autoCapitalize`).
* Support for additional SVG properties (`rx`, `ry`).
* Support for using `getInitialState` and `getDefaultProps` in mixins.
* Support mounting into iframes.
* Bug fixes for controlled form components.
* Bug fixes for SVG element creation.
* Added `React.version`.
* Added `React.isValidClass` - Used to determine if a value is a valid component constructor.
* Removed `React.autoBind` - This was deprecated in v0.4 and now properly removed.
* Renamed `React.unmountAndReleaseReactRootNode` to `React.unmountComponentAtNode`.
* Began laying down work for refined performance analysis.
* Better support for server-side rendering - [react-page](https://github.com/facebook/react-page) has helped improve the stability for server-side rendering.
* Made it possible to use React in environments enforcing a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy). This also makes it possible to use React to build Chrome extensions.
### React with Addons (New!)
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](/react/docs/addons.html).
### JSX
* No longer transform `class` to `className` as part of the transform! This is a breaking change - if you were using `class`, you *must* change this to `className` or your components will be visually broken.
* Added warnings to the in-browser transformer to make it clear it is not intended for production use.
* Improved compatibility for Windows
* Improved support for maintaining line numbers when transforming.

View File

@@ -0,0 +1,25 @@
---
title: "React v0.5.1"
layout: post
author: Paul O'Shannessy
---
This release focuses on fixing some small bugs that have been uncovered over the past two weeks. I would like to thank everybody involved, specifically members of the community who fixed half of the issues found. Thanks to [Ben Alpert][1], [Andrey Popp][2], and [Laurence Rowe][3] for their contributions!
## Changelog
### React
* Fixed bug with `<input type="range">` and selection events.
* Fixed bug with selection and focus.
* Made it possible to unmount components from the document root.
* Fixed bug for `disabled` attribute handling on non-`<input>` elements.
### React with Addons
* Fixed bug with transition and animation event detection.
[1]: https://github.com/spicyj
[2]: https://github.com/andreypopp
[3]: https://github.com/lrowe

View File

@@ -0,0 +1,143 @@
---
title: "Thinking in React"
layout: post
author: Pete Hunt
---
React is, in my opinion, the premier way to build big, fast Web apps with JavaScript. It's scaled very well for us at Facebook and Instagram.
One of the many great parts of React is how it makes you think about apps as you build them. In this post I'll walk you through the thought process of building a searchable product data table using React.
## Start with a mock
Imagine that we already have a JSON API and a mock from our designer. Our designer apparently isn't very good because the mock looks like this:
![Mockup](/react/img/blog/thinking-in-react-mock.png)
Our JSON API returns some data that looks like this:
```
[
{category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
{category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
{category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
{category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
{category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
{category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
];
```
## Step 1: break the UI into a component hierarchy
The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you're working with a designer they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!
But how do you know what should be its own component? Just use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing it should be decomposed into smaller subcomponents.
Since you're often displaying a JSON data model to a user, you'll find that if your model was built correctly your UI (and therefore your component structure) will map nicely onto it. That's because user interfaces and data models tend to adhere to the same *information architecture* which means the work of separating your UI into components is often trivial. Just break it up into components that represent exactly one piece of your data model.
![Component diagram](/react/img/blog/thinking-in-react-components.png)
You'll see here that we have five components in our simple app. I've italicized the data each component represents.
1. **`FilterableProductTable` (orange):** contains the entirety of the example
2. **`SearchBar` (blue):** receives all *user input*
3. **`ProductTable` (green):** displays and filters the *data collection* based on *user input*
4. **`ProductCategoryRow` (turquoise):** displays a heading for each *category*
5. **`ProductRow` (red):** displays a row for each *product*
If you look at `ProductTable` you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference and there's an argument to be made either way. For this example I left it as part of `ProductTable` because it is part of rendering the *data collection* which is `ProductTable`'s responsibility. However if this header grows to be complex (i.e. if we were to add affordances for sorting) it would certainly make sense to make this its own `ProductTableHeader` component.
Now that we've identified the components in our mock, let's arrange them into a hierarchy. This is easy. Components that appear within another component in the mock should appear as a child in the hierarchy:
* `FilterableProductTable`
* `SearchBar`
* `ProductTable`
* `ProductCategoryRow`
* `ProductRow`
## Step 2: Build a static version in React
<iframe width="100%" height="300" src="http://jsfiddle.net/6wQMG/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
Now that you have your component hierarchy it's time to start implementing your app. The easiest way is to build a version that takes your data model and renders the UI but has no interactivity. It's easiest to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing. We'll see why.
To build a static version of your app that renders your data model you'll want to build components that reuse other components and pass data using *props*. *props* are a way of passing data from parent to child. If you're familiar with the concept of *state*, **don't use state at all** to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app you don't need it.
You can build top-down or bottom-up. That is, you can either start with building the components higher up in the hierarchy (i.e. starting with `FilterableProductTable`) or with the ones lower in it (`ProductRow`). In simpler examples it's usually easier to go top-down and on larger projects it's easier to go bottom-up and write tests as you build.
At the end of this step you'll have a library of reusable components that render your data model. The components will only have `render()` methods since this is a static version of your app. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. If you make a change to your underlying data model and call `renderComponent()` again the UI will be updated. It's easy to see how your UI is updated and where to make changes since there's nothing complicated going on since React's **one-way data flow** (also called *one-way binding*) keeps everything modular, easy to reason about, and fast.
Simply refer to the [React docs](http://facebook.github.io/react/docs/) if you need help executing this step.
### A brief interlude: props vs state
There are two types of "model" data in React: props and state. It's important to understand the distinction between the two; skim [the official React docs](http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html) if you aren't sure what the difference is.
## Step 3: Identify the minimal (but complete) representation of UI state
To make your UI interactive you need to be able to trigger changes to your underlying data model. React makes this easy with **state**.
To build your app correctly you first need to think of the minimal set of mutable state that your app needs. The key here is DRY: *Don't Repeat Yourself*. Figure out what the absolute minimal representation of the state of your application needs to be and compute everything else you need on-demand. For example, if you're building a TODO list, just keep an array of the TODO items around; don't keep a separate state variable for the count. Instead, when you want to render the TODO count simply take the length of the TODO items array.
Think of all of the pieces of data in our example application. We have:
* The original list of products
* The search text the user has entered
* The value of the checkbox
* The filtered list of products
Let's go through each one and figure out which one is state. Simply ask three questions about each piece of data:
1. Is it passed in from a parent via props? If so, it probably isn't state.
2. Does it change over time? If not, it probably isn't state.
3. Can you compute it based on any other state or props in your component? If so, it's not state.
The original list of products is passed in as props, so that's not state. The search text and the checkbox seem to be state since they change over time and can't be computed from anything. And finally, the filtered list of products isn't state because it can be computed by combining the original list of products with the search text and value of the checkbox.
So finally, our state is:
* The search text the user has entered
* The value of the checkbox
## Step 4: Identify where your state should live
<iframe width="100%" height="300" src="http://jsfiddle.net/QvHnx/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
OK, so we've identified what the minimal set of app state is. Next we need to identify which component mutates, or *owns*, this state.
Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. **This is often the most challenging part for newcomers to understand,** so follow these steps to figure it out:
For each piece of state in your application:
* Identify every component that renders something based on that state.
* Find a common owner component (a single component above all the components that need the state in the hierarchy).
* Either the common owner or another component higher up in the hierarchy should own the state.
* If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.
Let's run through this strategy for our application:
* `ProductTable` needs to filter the product list based on state and `SearchBar` needs to display the search text and checked state.
* The common owner component is `FilterableProductTable`.
* It conceptually makes sense for the filter text and checked value to live in `FilterableProductTable`
Cool, so we've decided that our state lives in `FilterableProductTable`. First, add a `getInitialState()` method to `FilterableProductTable` that returns `{filterText: '', inStockOnly: false}` to reflect the initial state of your application. Then pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as a prop. Finally, use these props to filter the rows in `ProductTable` and set the values of the form fields in `SearchBar`.
You can start seeing how your application will behave: set `filterText` to `"ball"` and refresh your app. You'll see the data table is updated correctly.
## Step 5: Add inverse data flow
<iframe width="100%" height="300" src="http://jsfiddle.net/3Vs3Q/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
So far we've built an app that renders correctly as a function of props and state flowing down the hierarchy. Now it's time to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
React makes this data flow explicit to make it easy to understand how your program works, but it does require a little more typing than traditional two-way data binding. React provides an add-on called `ReactLink` to make this pattern as convenient as two-way binding, but for the purpose of this post we'll keep everything explicit.
If you try to type or check the box in the current version of the example you'll see that React ignores your input. This is intentional, as we've set the `value` prop of the `input` to always be equal to the `state` passed in from `FilterableProductTable`.
Let's think about what we want to happen. We want to make sure that whenever the user changes the form we update the state to reflect the user input. Since components should only update their own state, `FilterableProductTable` will pass a callback to `SearchBar` that will fire whenever the state should be updated. We can use the `onChange` event on the inputs to be notified of it. And the callback passed by `FilterableProductTable` will call `setState()` and the app will be updated.
Though this sounds like a lot it's really just a few lines of code. And it's really explicit how your data is flowing throughout the app.
## And that's it
Hopefully this gives you an idea of how to think about building components and applications with React. While it may be a little more typing than you're used to, remember that code is read far more than it's written, and it's extremely easy to read this modular, explicit code. As you start to build large libraries of components you'll appreciate this explicitness and modularity, and with code reuse your lines of code will start to shrink :)

View File

@@ -0,0 +1,125 @@
---
title: "Community Round-up #10"
layout: post
author: Vjeux
---
This is the 10th round-up already and React has come quite far since it was open sourced. Almost all new web projects at Khan Academy, Facebook, and Instagram are being developed using React. React has been deployed in a variety of contexts: a Chrome extension, a Windows 8 application, mobile websites, and desktop websites supporting Internet Explorer 8! Language-wise, React is not only being used within JavaScript but also CoffeeScript and ClojureScript.
The best part is that no drastic changes have been required to support all those use cases. Most of the efforts were targeted at polishing edge cases, performance improvements, and documentation.
## Khan Academy - Officially moving to React
[Joel Burget](http://joelburget.com/) announced at Hack Reactor that new front-end code at Khan Academy should be written in React!
> How did we get the rest of the team to adopt React? Using interns as an attack vector! Most full-time devs had already been working on their existing projects for a while and weren't looking to try something new at the time, but our class of summer interns was just arriving. For whatever reason, a lot of them decided to try React for their projects. Then mentors became exposed through code reviews or otherwise touching the new code. In this way React knowledge diffused to almost the whole team over the summer.
>
> Since the first React checkin on June 5, we've somehow managed to accumulate 23500 lines of jsx (React-flavored js) code. Which is terrifying in a way - that's a lot of code - but also really exciting that it was picked up so quickly.
>
> We held three meetings about how we should proceed with React. At the first two we decided to continue experimenting with React and deferred a final decision on whether to adopt it. At the third we adopted the policy that new code should be written in React.
>
> I'm excited that we were able to start nudging code quality forward. However, we still have a lot of work to do! One of the selling points of this transition is adopting a uniform frontend style. We're trying to upgrade all the code from (really old) pure jQuery and (regular old) Backbone views / Handlebars to shiny React. At the moment all we've done is introduce more fragmentation. We won't be gratuitously updating working code (if it ain't broke, don't fix it), but are seeking out parts of the codebase where we can shoot two birds with one stone by rewriting in React while fixing bugs or adding functionality.
>
> [Read the full article](http://joelburget.com/backbone-to-react/)
## React: Rethinking best practices
[Pete Hunt](http://www.petehunt.net/)'s talk at JSConf EU 2013 is now available in video.
<figure><iframe width="600" height="370" src="//www.youtube.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe></figure>
## Server-side React with PHP
[Stoyan Stefanov](http://www.phpied.com/)'s series of articles on React has two new entries on how to execute React on the server to generate the initial page load.
> This post is an initial hack to have React components render server-side in PHP.
>
> - Problem: Build web UIs
> - Solution: React
> - Problem: UI built in JS is anti-SEO (assuming search engines are still noscript) and bad for perceived performance (blank page till JS arrives)
> - Solution: [React page](https://github.com/facebook/react-page) to render the first view
> - Problem: Can't host node.js apps / I have tons of PHP code
> - Solution: Use PHP then!
>
> [**Read part 1 ...**](http://www.phpied.com/server-side-react-with-php/)
>
> [**Read part 2 ...**](http://www.phpied.com/server-side-react-with-php-part-2/)
>
> Rendered markup on the server:
> <figure>[![](/react/img/blog/react-php.png)](http://www.phpied.com/server-side-react-with-php-part-2/)</figure>
## TodoMVC Benchmarks
Webkit has a [TodoMVC Benchmark](https://github.com/WebKit/webkit/tree/master/PerformanceTests/DoYouEvenBench) that compares different frameworks. They recently included React and here are the results (average of 10 runs in Chrome 30):
- **AngularJS:** 4043ms
- **AngularJSPerf:** 3227ms
- **BackboneJS:** 1874ms
- **EmberJS:** 6822ms
- **jQuery:** 14628ms
- **React:** 2864ms
- **VanillaJS:** 5567ms
[Try it yourself!](http://www.petehunt.net/react/tastejs/benchmark.html)
Please don't take those numbers too seriously, they only reflect one very specific use case and are testing code that wasn't written with performance in mind.
Even though React scores as one of the fastest frameworks in the benchmark, the React code is simple and idiomatic. The only performance tweak used is the following function:
```javascript
/**
* This is a completely optional performance enhancement that you can implement
* on any React component. If you were to delete this method the app would still
* work correctly (and still be very performant!), we just use it as an example
* of how little code it takes to get an order of magnitude performance improvement.
*/
shouldComponentUpdate: function (nextProps, nextState) {
return (
nextProps.todo.id !== this.props.todo.id ||
nextProps.todo !== this.props.todo ||
nextProps.editing !== this.props.editing ||
nextState.editText !== this.state.editText
);
},
```
By default, React "re-renders" all the components when anything changes. This is usually fast enough that you don't need to care. However, you can provide a function that can tell whether there will be any change based on the previous and next states and props. If it is faster than re-rendering the component, then you get a performance improvement.
The fact that you can control when components are rendered is a very important characteristic of React as it gives you control over its performance. We are going to talk more about performance in the future, stay tuned.
## Guess the filter
[Connor McSheffrey](http://conr.me) implemented a small game using React. The goal is to guess which filter has been used to create the Instagram photo.
<figure>[![](/react/img/blog/guess_filter.jpg)](http://guessthefilter.com/)</figure>
## React vs FruitMachine
[Andrew Betts](http://trib.tv/), director of the [Financial Times Labs](http://labs.ft.com/), posted an article comparing [FruitMachine](https://github.com/ftlabs/fruitmachine) and React.
> Eerily similar, no? Maybe Facebook was inspired by Fruit Machine (after all, we got there first), but more likely, it just shows that this is a pretty decent way to solve the problem, and great minds think alike. We're graduating to a third phase in the evolution of web best practice - from intermingling of markup, style and behaviour, through a phase in which those concerns became ever more separated and encapsulated, and finally to a model where we can do that separation at a component level. Developments like Web Components show the direction the web community is moving, and frameworks like React and Fruit Machine are in fact not a lot more than polyfills for that promised behaviour to come.
>
> [Read the full article...](http://labs.ft.com/2013/10/client-side-layout-engines-react-vs-fruitmachine/)
Even though we weren't inspired by FruitMachine (React has been used in production since before FruitMachine was open sourced), it's great to see similar technologies emerging and becoming popular.
## React Brunch
[Matthew McCray](http://elucidata.net/) implemented [react-brunch](https://npmjs.org/package/react-brunch), a JSX compilation step for [Brunch](http://brunch.io/).
> Adds React support to brunch by automatically compiling `*.jsx` files.
>
> You can configure react-brunch to automatically insert a react header (`/** @jsx React.DOM */`) into all `*.jsx` files. Disabled by default.
>
> Install the plugin via npm with `npm install --save react-brunch`.
>
> [Read more...](https://npmjs.org/package/react-brunch)
## Random Tweet
I'm going to start adding a tweet at the end of each round-up. We'll start with this one:
<blockquote class="twitter-tweet"><p>This weekend <a href="https://twitter.com/search?q=%23angular&amp;src=hash">#angular</a> died for me. Meet new king <a href="https://twitter.com/search?q=%23reactjs&amp;src=hash">#reactjs</a></p>&mdash; Eldar Djafarov &#x30C3; (@edjafarov) <a href="https://twitter.com/edjafarov/statuses/397033796710961152">November 3, 2013</a></blockquote>

View File

@@ -0,0 +1,92 @@
---
title: "Community Round-up #11"
layout: post
author: Vjeux
---
This round-up is the proof that React has taken off from its Facebook's root: it features three in-depth presentations of React done by external people. This is awesome, keep them coming!
## Super VanJS 2013 Talk
[Steve Luscher](https://github.com/steveluscher) working at [LeanPub](https://leanpub.com/) made a 30 min talk at [Super VanJS](https://twitter.com/vanjs). He does a remarkable job at explaining why React is so fast with very exciting demos using the HTML5 Audio API.
<figure><iframe width="600" height="338" src="//www.youtube.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe></figure>
## React Tips
[Connor McSheffrey](http://connormcsheffrey.com/) and [Cheng Lou](https://github.com/chenglou) added a new section to the documentation. It's a list of small tips that you will probably find useful while working on React. Since each article is very small and focused, we [encourage you to contribute](http://facebook.github.io/react/tips/introduction.html)!
- [Inline Styles](http://facebook.github.io/react/tips/inline-styles.html)
- [If-Else in JSX](http://facebook.github.io/react/tips/if-else-in-JSX.html)
- [Self-Closing Tag](http://facebook.github.io/react/tips/self-closing-tag.html)
- [Maximum Number of JSX Root Nodes](http://facebook.github.io/react/tips/maximum-number-of-jsx-root-nodes.html)
- [Shorthand for Specifying Pixel Values in style props](http://facebook.github.io/react/tips/style-props-value-px.html)
- [Type of the Children props](http://facebook.github.io/react/tips/children-props-type.html)
- [Value of null for Controlled Input](http://facebook.github.io/react/tips/controlled-input-null-value.html)
- [`componentWillReceiveProps` Not Triggered After Mounting](http://facebook.github.io/react/tips/componentWillReceiveProps-not-triggered-after-mounting.html)
- [Props in getInitialState Is an Anti-Pattern](http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html)
- [DOM Event Listeners in a Component](http://facebook.github.io/react/tips/dom-event-listeners.html)
- [Load Initial Data via AJAX](http://facebook.github.io/react/tips/initial-ajax.html)
- [False in JSX](http://facebook.github.io/react/tips/false-in-jsx.html)
## Intro to the React Framework
[Pavan Podila](http://blog.pixelingene.com/) wrote an in-depth introduction to React on TutsPlus. This is definitively worth reading.
> Within a component-tree, data should always flow down. A parent-component should set the props of a child-component to pass any data from the parent to the child. This is termed as the Owner-Owned pair. On the other hand user-events (mouse, keyboard, touches) will always bubble up from the child all the way to the root component, unless handled in between.
<figure>[![](/react/img/blog/tutsplus.png)](http://dev.tutsplus.com/tutorials/intro-to-the-react-framework--net-35660)</figure>
>
> [Read the full article ...](http://dev.tutsplus.com/tutorials/intro-to-the-react-framework--net-35660)
## 140-characters textarea
[Brian Kim](https://github.com/brainkim) wrote a small textarea component that gradually turns red as you reach the 140-characters limit. Because he only changes the background color, React is smart enough not to mess with the text selection.
<p data-height="178" data-theme-id="0" data-slug-hash="FECGb" data-user="brainkim" data-default-tab="result" class='codepen'>See the Pen <a href='http://codepen.io/brainkim/pen/FECGb'>FECGb</a> by Brian Kim (<a href='http://codepen.io/brainkim'>@brainkim</a>) on <a href='http://codepen.io'>CodePen</a></p>
<script async src="//codepen.io/assets/embed/ei.js"></script>
## Genesis Skeleton
[Eric Clemmons](http://ericclemmons.github.io/) is working on a "Modern, opinionated, full-stack starter kit for rapid, streamlined application development". The version 0.4.0 has just been released and has first-class support for React.
<figure>[![](/react/img/blog/genesis_skeleton.png)](http://genesis-skeleton.com/)</figure>
## AgFlow Talk
[Robert Zaremba](http://rz.scale-it.pl/) working on [AgFlow](http://www.agflow.com/) recently talked in Poland about React.
> In a nutshell, I presented why we chose React among other available options (ember.js, angular, backbone ...) in AgFlow, where Im leading an application development.
>
> During the talk a wanted to highlight that React is not about implementing a Model, but a way to construct visible components with some state. React is simple. It is super simple, you can learn it in 1h. On the other hand what is model? Which functionality it should provide? React does one thing and does it the best (for me)!
>
> [Read the full article...](http://rz.scale-it.pl/2013/10/20/frontend_components_in_react.html)
<figure><iframe src="https://docs.google.com/presentation/d/1JSFbjCuuexwOHCeHWBMNRIJdyfD2Z0ZQwX65WOWkfaI/embed?start=false" frameborder="0" width="600" height="468" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"> </iframe></figure>
## JSX
[Todd Kennedy](http://tck.io/) working at Cond&eacute; Nast wrote [JSXHint](https://github.com/CondeNast/JSXHint) and explains in a blog post his perspective on JSX.
> Lets start with the elephant in the room: JSX?
> Is this some sort of template language? Specifically no. This might have been the first big stumbling block. What looks like to be a templating language is actually an in-line DSL that gets transpiled directly into JavaScript by the JSX transpiler.
>
> Creating elements in memory is quick -- copying those elements into the DOM is where the slowness occurs. This is due to a variety of issues, most namely reflow/paint. Changing the items in the DOM causes the browser to re-paint the display, apply styles, etc. We want to keep those operations to an absolute minimum, especially if we're dealing with something that needs to update the DOM frequently.
>
> [Read the full article...](http://tck.io/posts/jsxhint_and_react.html)
## Photo Gallery
[Maykel Loomans](http://miekd.com/), designer at Instagram, wrote a gallery for photos he shot using React.
<figure>[![](/react/img/blog/xoxo2013.png)](http://photos.miekd.com/xoxo2013/)</figure>
## Random Tweet
<img src="/react/img/blog/steve_reverse.gif" style="float: right;" />
<div style="width: 320px;"><blockquote class="twitter-tweet"><p>I think this reversed gif of Steve Urkel best describes my changing emotions towards the React Lib <a href="http://t.co/JoX0XqSXX3">http://t.co/JoX0XqSXX3</a></p>&mdash; Ryan Seddon (@ryanseddon) <a href="https://twitter.com/ryanseddon/statuses/398572848802852864">November 7, 2013</a></blockquote></div>

View File

@@ -0,0 +1,23 @@
---
title: "React v0.5.2, v0.4.2"
layout: post
author: Paul O'Shannessy
---
Today we're releasing an update to address a potential XSS vulnerability that can arise when using user data as a `key`. Typically "safe" data is used for a `key`, for example, an id from your database, or a unique hash. However there are cases where it may be reasonable to use user generated content. A carefully crafted piece of content could result in arbitrary JS execution. While we make a very concerted effort to ensure all text is escaped before inserting it into the DOM, we missed one case. Immediately following the discovery of this vulnerability, we performed an audit to ensure we this was the only such vulnerability.
This only affects v0.5.x and v0.4.x. Versions in the 0.3.x family are unaffected.
Updated versions are available for immediate download via npm, bower, and on our [download page][download].
We take security very seriously at Facebook. For most of our products, users don't need to know that a security issue has been fixed. But with libraries like React, we need to make sure developers using React have access to fixes to keep their users safe.
While we've encouraged responsible disclosure as part of [Facebook's whitehat bounty program][bounty] since we launched, we don't have a good process for notifying our users. Hopefully we don't need to use it, but moving forward we'll set up a little bit more process to ensure the safety of our users. Ember.js has [an excellent policy][ember] which we may use as our model.
You can learn more about the vulnerability discussed here: [CVE-2013-7035][cve].
[download]: http://facebook.github.io/react/downloads.html
[bounty]: https://www.facebook.com/whitehat/
[ember]: http://emberjs.com/security/
[cve]: https://groups.google.com/forum/#!topic/reactjs/OIqxlB2aGfU

View File

@@ -0,0 +1,48 @@
---
title: "React v0.8"
layout: post
author: Paul O'Shannessy
---
I'll start by answering the obvious question:
> What happened to 0.6 and 0.7?
It's become increasingly obvious since our launch in May that people want to use React on the server. With the server-side rendering abilities, that's a perfect fit. However using the same copy of React on the server and then packaging it up for the client is surprisingly a harder problem. People have been using our `react-tools` module which includes React, but when browserifying that ends up packaging all of `esprima` and some other dependencies that aren't needed on the client. So we wanted to make this whole experience better.
We talked with [Jeff Barczewski][jeff] who was the owner of the `react` module on npm. He was kind enough to transition ownership to us and release his package under a different name: `autoflow`. I encourage you to [check it out][autoflow] if you're writing a lot of asynchronous code. In order to not break all of `react`'s current users of 0.7.x, we decided to bump our version to 0.8 and skip the issue entirely. We're also including a warning if you use our `react` module like you would use the previous package.
In order to make the transition to 0.8 for our current users as painless as possible, we decided to make 0.8 primarily a bug fix release on top of 0.5. No public APIs were changed (even if they were already marked as deprecated). We haven't added any of the new features we have in master, though we did take the opportunity to pull in some improvements to internals.
We hope that by releasing `react` on npm, we will enable a new set of uses that have been otherwise difficult. All feedback is welcome!
## Changelog
### React
* Added support for more attributes:
* `rows` & `cols` for `<textarea>`
* `defer` & `async` for `<script>`
* `loop` for `<audio>` & `<video>`
* `autoCorrect` for form fields (a non-standard attribute only supported by mobile WebKit)
* Improved error messages
* Fixed Selection events in IE11
* Added `onContextMenu` events
### React with Addons
* Fixed bugs with TransitionGroup when children were undefined
* Added support for `onTransition`
### react-tools
* Upgraded `jstransform` and `esprima-fb`
### JSXTransformer
* Added support for use in IE8
* Upgraded browserify, which reduced file size by ~65KB (16KB gzipped)
[jeff]: https://github.com/jeffbski
[autoflow]: https://github.com/jeffbski/autoflow

View File

@@ -0,0 +1,105 @@
---
title: "Community Round-up #12"
layout: post
author: Vjeux
---
React got featured on the front-page of Hacker News thanks to the Om library. If you try it out for the first time, take a look at the [docs](/react/docs/getting-started.html) and do not hesitate to ask questions on the [Google Group](http://groups.google.com/group/reactjs), [IRC](irc://chat.freenode.net/reactjs) or [Stack Overflow](http://stackoverflow.com/questions/tagged/reactjs). We are trying our best to help you out!
## The Future of Javascript MVC
[David Nolen](http://swannodette.github.io/) announced Om, a thin wrapper on-top of React in ClojureScript. It stands out by only using immutable data structures. This unlocks the ability to write a very efficient [shouldComponentUpdate](http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate) and get huge performance improvements on some tasks.
> We've known this for some time over here in the ClojureScript corner of the world - all of our collections are immutable and modeled directly on the original Clojure versions written in Java. Modern JavaScript engines have now been tuned to the point that it's no longer uncommon to see collection performance within 2.5X of the Java Virtual Machine.
>
> Wait, wait, wait. What does the performance of persistent data structures have to do with the future of JavaScript MVCs?
>
> A whole lot.
> <figure>[![](/react/img/blog/om-backbone.png)](http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/)</figure>
>
> [Read the full article...](http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/)
## Scroll Position with React
Managing the scroll position when new content is inserted is usually very tricky to get right. [Vjeux](http://blog.vjeux.com/) discovered that [componentWillUpdate](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate) and [componentDidUpdate](http://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate) were triggered exactly at the right time to manage the scroll position.
> We can check the scroll position before the component has updated with componentWillUpdate and scroll if necessary at componentDidUpdate
>
> ```
componentWillUpdate: function() {
var node = this.getDOMNode();
this.shouldScrollBottom =
(node.scrollTop + node.offsetHeight) === node.scrollHeight;
},
componentDidUpdate: function() {
if (this.shouldScrollBottom) {
var node = this.getDOMNode();
node.scrollTop = node.scrollHeight
}
},
```
>
> [Check out the blog article...](http://blog.vjeux.com/2013/javascript/scroll-position-with-react.html)
## Lights Out
React declarative approach is well suited to write games. [Cheng Lou](https://github.com/chenglou) wrote the famous Lights Out game in React. It's a good example of use of [TransitionGroup](http://facebook.github.io/react/docs/animation.html) to implement animations.
<figure>[![](/react/img/blog/lights-out.png)](http://chenglou.github.io/react-lights-out/)</figure>
[Try it out!](http://chenglou.github.io/react-lights-out/)
## Reactive Table Bookmarklet
[Stoyan Stefanov](http://www.phpied.com/) wrote a bookmarklet to process tables on the internet. It adds a little "pop" button that expands to a full-screen view with sorting, editing and export to csv and json.
<figure>[![](/react/img/blog/reactive-bookmarklet.png)](http://www.phpied.com/reactivetable-bookmarklet/)</figure>
[Check out the blog post...](http://www.phpied.com/reactivetable-bookmarklet/)
## MontageJS Tutorial in React
[Ross Allen](https://twitter.com/ssorallen) implemented [MontageJS](http://montagejs.org/)'s [Reddit tutorial](http://montagejs.org/docs/tutorial-reddit-client-with-montagejs.html) in React. This is a good opportunity to compare the philosophies of the two libraries.
<iframe width="100%" height="300" src="http://jsfiddle.net/ssorallen/fEsYt/embedded/result,html,js" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
[View the source on JSFiddle...](http://jsfiddle.net/ssorallen/fEsYt/)
## Writing Good React Components
[William Högman Rudenmalm](http://blog.whn.se/) wrote an article on how to write good React components. This is full of good advice.
> The idea of dividing software into smaller parts or components is hardly new - It is the essance of good software. The same principles that apply to software in general apply to building React components. That doesnt mean that writing good React components is just about applying general rules.
>
> The web offers a unique set of challenges, which React offers interesting solutions to. First and foremost among these solutions is the what is called the Mock DOM. Rather than having user code interface with the DOM in a direct fashion, as is the case with most DOM manipulation libraries.
>
> You build a model of how you want the DOM end up like. React then inserts this model into the DOM. This is very useful for updates because React simply compares the model or mock DOM against the actual DOM, and then only updates based on the difference between the two states.
>
> [Read the full article ...](http://blog.whn.se/post/69621609605/writing-good-react-components)
## Hoodie React TodoMVC
[Sven Lito](http://svenlito.com/) integrated the React TodoMVC example within an [Hoodie](http://hood.ie/) web app environment. This should let you get started using Hoodie and React.
```
hoodie new todomvc -t "hoodiehq/hoodie-react-todomvc"
```
[Check out on GitHub...](https://github.com/hoodiehq/hoodie-react-todomvc)
## JSX Compiler
Ever wanted to have a quick way to see what a JSX tag would be converted to? [Tim Yung](http://www.yungsters.com/) made a page for it.
<figure>[![](/react/img/blog/jsx-compiler.png)](http://facebook.github.io/react/jsx-compiler.html)</figure>
[Try it out!](http://facebook.github.io/react/jsx-compiler.html)
## Random Tweet
<center><blockquote class="twitter-tweet" lang="en"><p>.<a href="https://twitter.com/jordwalke">@jordwalke</a> lays down some truth <a href="http://t.co/AXAn0UlUe3">http://t.co/AXAn0UlUe3</a>, optimizing your JS application shouldn&#39;t force you to rewrite so much code <a href="https://twitter.com/search?q=%23reactjs&amp;src=hash">#reactjs</a></p>&mdash; David Nolen (@swannodette) <a href="https://twitter.com/swannodette/statuses/413780079249215488">December 19, 2013</a></blockquote></center>

View File

@@ -0,0 +1,119 @@
---
title: "Community Round-up #13"
layout: post
author: Vjeux
---
Happy holidays! This blog post is a little-late Christmas present for all the React users. Hopefully it will inspire you to write awesome web apps in 2014!
## React Touch
[Pete Hunt](http://www.petehunt.net/) wrote three demos showing that React can be used to run 60fps native-like experiences on mobile web. A frosted glass effect, an image gallery with 3d animations and an infinite scroll view.
<figure><iframe src="//player.vimeo.com/video/79659941" width="220" height="400" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></figure>
[Try out the demos!](http://petehunt.github.io/react-touch/)
## Introduction to React
[Stoyan Stefanov](http://www.phpied.com/) talked at Joe Dev On Tech about React. He goes over all the features of the library and ends with a concrete example.
<figure><iframe width="560" height="315" src="//www.youtube.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe></figure>
## JSX: E4X The Good Parts
JSX is often compared to the now defunct E4X, [Vjeux](http://blog.vjeux.com/) went over all the E4X features and explained how JSX is different and hopefully doesn't repeat the same mistakes.
> E4X (ECMAScript for XML) is a Javascript syntax extension and a runtime to manipulate XML. It was promoted by Mozilla but failed to become mainstream and is now deprecated. JSX was inspired by E4X. In this article, I'm going to go over all the features of E4X and explain the design decisions behind JSX.
>
> **Historical Context**
>
> E4X has been created in 2002 by John Schneider. This was the golden age of XML where it was being used for everything: data, configuration files, code, interfaces (DOM) ... E4X was first implemented inside of Rhino, a Javascript implementation from Mozilla written in Java.
>
> [Continue reading ...](http://blog.vjeux.com/2013/javascript/jsx-e4x-the-good-parts.html)
## React + Socket.io
[Geert Pasteels](http://enome.be/nl) made a small experiment with Socket.io. He wrote a very small mixin that synchronizes React state with the server. Just include this mixin to your React component and it is now live!
```javascript
changeHandler: function (data) {
if (!_.isEqual(data.state, this.state) && this.path === data.path) {
this.setState(data.state);
}
},
componentDidMount: function (root) {
this.path = utils.nodePath(root);
socket.on('component-change', this.changeHandler);
},
componentWillUpdate: function (props, state) {
socket.emit('component-change', { path: this.path, state: state });
},
componentWillUnmount: function () {
socket.removeListener('component-change', this.change);
}
```
[Check it out on GitHub...](https://github.com/Enome/react.io)
## cssobjectify
[Andrey Popp](http://andreypopp.com/) implemented a source transform that takes a CSS file and converts it to JSON. This integrates pretty nicely with React.
```javascript
/* style.css */
MyComponent {
font-size: 12px;
background-color: red;
}
/* myapp.js */
var React = require('react-tools/build/modules/React');
var Styles = require('./styles.css');
var MyComponent = React.createClass({
render: function() {
return (
<div style={Styles.MyComponent}>
Hello, world!
</div>
)
}
});
```
[Check it out on GitHub...](https://github.com/andreypopp/cssobjectify)
## ngReact
[David Chang](http://davidandsuzi.com/) working at [HasOffer](http://www.hasoffers.com/) wanted to speed up his Angular app and replaced Angular primitives by React at different layers. When using React naively it is 67% faster, but when combining it with angular's transclusion it is 450% slower.
> Rendering this takes 803ms for 10 iterations, hovering around 35 and 55ms for each data reload (that's 67% faster). You'll notice that the first load takes a little longer than successive loads, and the second load REALLY struggles - here, it's 433ms, which is more than half of the total time!
> <figure>[![](/react/img/blog/ngreact.png)](http://davidandsuzi.com/ngreact-react-components-in-angular/)</figure>
>
> [Read the full article...](http://davidandsuzi.com/ngreact-react-components-in-angular/)
## vim-jsx
[Max Wang](https://github.com/mxw) made a vim syntax highlighting and indentation plugin for vim.
> Syntax highlighting and indenting for JSX. JSX is a JavaScript syntax transformer which translates inline XML document fragments into JavaScript objects. It was developed by Facebook alongside React.
>
> This bundle requires pangloss's [vim-javascript](https://github.com/pangloss/vim-javascript) syntax highlighting.
>
> Vim support for inline XML in JS is remarkably similar to the same for PHP.
>
> [View on GitHub...](https://github.com/mxw/vim-jsx)
## Random Tweet
<center><blockquote class="twitter-tweet" lang="en"><p>I may be starting to get annoying with this, but ReactJS is really exciting. I truly feel the virtual DOM is a game changer.</p>&mdash; Eric Florenzano (@ericflo) <a href="https://twitter.com/ericflo/statuses/413842834974732288">December 20, 2013</a></blockquote></center>

View File

@@ -0,0 +1,19 @@
---
title: "React Chrome Developer Tools"
layout: post
author: Sebastian Markbåge
---
With the new year, we thought you'd enjoy some new tools for debugging React code. Today we're releasing the [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), an extension to the Chrome Developer Tools. [Download them from the Chrome Web Store](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi).
<figure><iframe width="560" height="315" src="//www.youtube.com/embed/Cey7BS6dE0M" frameborder="0" allowfullscreen></iframe></figure>
You will get a new tab titled "React" in your Chrome DevTools. This tab shows you a list of the root React Components that are rendered on the page as well as the subcomponents that each root renders.
Selecting a Component in this tab allows you to view and edit its props and state in the panel on the right. In the breadcrumbs at the bottom, you can inspect the selected Component, the Component that created it, the Component that created that one, and so on.
When you inspect a DOM element using the regular Elements tab, you can switch over to the React tab and the corresponding Component will be automatically selected. The Component will also be automatically selected if you have a breakpoint within its render phase. This allows you to step through the render tree and see how one Component affects another one.
<figure>[![](/react/img/blog/react-dev-tools.jpg)](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi)</figure>
We hope these tools will help your team better understand your component hierarchy and track down bugs. We're very excited about this initial launch and appreciate any feedback you may have. As always, we also accept [pull requests on GitHub](https://github.com/facebook/react-devtools).

View File

@@ -0,0 +1,92 @@
---
title: "Community Round-up #14"
layout: post
author: Vjeux
---
The theme of this first round-up of 2014 is integration. I've tried to assemble a list of articles and projects that use React in various environments.
## React Baseline
React is only one-piece of your web application stack. [Mark Lussier](https://github.com/intabulas) shared his baseline stack that uses React along with Grunt, Browserify, Bower, Zepto, Director and Sass. This should help you get started using React for a new project.
> As I do more projects with ReactJS I started to extract a baseline to use when starting new projects. This is very opinionated and I change my opinion from time to time. This is by no ways perfect and in your opinion most likely wrong :).. which is why I love github
>
> I encourage you to fork, and make it right and submit a pull request!
>
> My current opinion is using tools like Grunt, Browserify, Bower and mutiple grunt plugins to get the job done. I also opted for Zepto over jQuery and the Flatiron Project's Director when I need a router. Oh and for the last little bit of tech that makes you mad, I am in the SASS camp when it comes to stylesheets
>
> [Check it out on GitHub...](https://github.com/intabulas/reactjs-baseline)
## Animal Sounds
[Josh Duck](http://joshduck.com/) used React in order to build a Windows 8 tablet app. This is a good example of a touch app written in React.
<figure>[![](/react/img/blog/animal-sounds.jpg)](http://apps.microsoft.com/windows/en-us/app/baby-play-animal-sounds/9280825c-2ed9-41c0-ba38-aa9a5b890bb9)</figure>
[Download the app...](http://apps.microsoft.com/windows/en-us/app/baby-play-animal-sounds/9280825c-2ed9-41c0-ba38-aa9a5b890bb9)
## React Rails Tutorial
[Selem Delul](http://selem.im) bundled the [React Tutorial](http://facebook.github.io/react/docs/tutorial.html) into a rails app. This is a good example on how to get started with a rails project.
> ```
git clone https://github.com/necrodome/react-rails-tutorial
cd react-rails-tutorial
bundle install
rake db:migrate
rails s
```
> Then visit http://localhost:3000/app to see the React application that is explained in the React Tutorial. Try opening multiple tabs!
>
> [View on GitHub...](https://github.com/necrodome/react-rails-tutorial)
## Mixing with Backbone
[Eldar Djafarov](http://eldar.djafarov.com/) implemented a mixin to link Backbone models to React state and a small abstraction to write two-way binding on-top.
<iframe width="100%" height="300" src="http://jsfiddle.net/djkojb/qZf48/13/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
[Check out the blog post...](http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/)
## React Infinite Scroll
[Guillaume Rivals](https://twitter.com/guillaumervls) implemented an InfiniteScroll component. This is a good example of a React component that has a simple yet powerful API.
```javascript
<InfiniteScroll
pageStart={0}
loadMore={loadFunc}
hasMore={true || false}
loader={<div className="loader">Loading ...</div>}>
{items} // <-- This is the "stuff" you want to load
</InfiniteScroll>
```
[Try it out on GitHub!](https://github.com/guillaumervls/react-infinite-scroll)
## Web Components Style
[Thomas Aylott](http://subtlegradient.com/) implemented an API that looks like Web Components but using React underneath.
<iframe width="100%" height="300" src="http://jsfiddle.net/SubtleGradient/ue2Aa/embedded/html,js,result" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
## React vs Angular
React is often compared with Angular. [Pete Hunt](http://skulbuny.com/2013/10/31/react-vs-angular/) wrote an opinionated post on the subject.
> First of all I think its important to evaluate technologies on objective rather than subjective features. “It feels nicer” or “its cleaner” arent valid reasons: performance, modularity, community size and ease of testing / integration with other tools are.
>
> Ive done a lot of work benchmarking, building apps, and reading the code of Angular to try to come up with a reasonable comparison between their ways of doing things.
>
> [Read the full post...](http://skulbuny.com/2013/10/31/react-vs-angular/)
## Random Tweet
<div><blockquote class="twitter-tweet" lang="en"><p>Really intrigued by React.js. I&#39;ve looked at all JS frameworks, and excepting <a href="https://twitter.com/serenadejs">@serenadejs</a> this is the first one which makes sense to me.</p>&mdash; Jonas Nicklas (@jonicklas) <a href="https://twitter.com/jonicklas/statuses/412640708755869696">December 16, 2013</a></blockquote></div>

View File

@@ -0,0 +1,126 @@
---
title: "Community Round-up #15"
layout: post
author: Jonas Gebhardt
---
Interest in React seems to have surged ever since David Nolen ([@swannodette](https://twitter.com/swannodette))'s introduction of [Om](https://github.com/swannodette/om) in his post ["The Future of Javascript MVC Frameworks"](http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/).
In this React Community Round-up, we are taking a closer look at React from a functional programming perspective.
## "React: Another Level of Indirection"
To start things off, Eric Normand ([@ericnormand](https://twitter.com/ericnormand)) of [LispCast](http://lispcast.com) makes the case for [React from a general functional programming standpoint](http://www.lispcast.com/react-another-level-of-indirection) and explains how React's "Virtual DOM provides the last piece of the Web Frontend Puzzle for ClojureScript".
> The Virtual DOM is an indirection mechanism that solves the difficult problem of DOM programming: how to deal with incremental changes to a stateful tree structure. By abstracting away the statefulness, the Virtual DOM turns the real DOM into an immediate mode GUI, which is perfect for functional programming.
>
> [Read the full post...](http://www.lispcast.com/react-another-level-of-indirection)
## Reagent: Minimalistic React for ClojureScript
Dan Holmsand ([@holmsand](https://twitter.com/holmsand)) created [Reagent](http://holmsand.github.io/reagent/), a simplistic ClojureScript API to React.
> It allows you to define efficient React components using nothing but plain ClojureScript functions and data, that describe your UI using a Hiccup-like syntax.
>
> The goal of Reagent is to make it possible to define arbitrarily complex UIs using just a couple of basic concepts, and to be fast enough by default that you rarely have to care about performance.
>
> [Check it out on Github...](http://holmsand.github.io/reagent/)
## Functional DOM programming
React's one-way data-binding naturally lends itself to a functional programming approach. Facebook's Pete Hunt ([@floydophone](https://twitter.com/floydophone)) explores how one would go about [writing web apps in a functional manner](https://medium.com/p/67d81637d43). Spoiler alert:
> This is React. Its not about templates, or data binding, or DOM manipulation. Its about using functional programming with a virtual DOM representation to build ambitious, high-performance apps with JavaScript.
>
> [Read the full post...](https://medium.com/p/67d81637d43)
Pete also explains this in detail at his #MeteorDevShop talk (about 30 Minutes):
<iframe width="560" height="315" src="//www.youtube.com/embed/Lqcs6hPOcFw?start=2963" frameborder="0" allowfullscreen></iframe>
## Kioo: Separating markup and logic
[Creighton Kirkendall](https://github.com/ckirkendall) created [Kioo](https://github.com/ckirkendall/kioo), which adds Enlive-style templating to React. HTML templates are separated from the application logic. Kioo comes with separate examples for both Om and Reagent.
A basic example from github:
```html
<!DOCTYPE html>
<html lang="en">
<body>
<header>
<h1>Header placeholder</h1>
<ul id="navigation">
<li class="nav-item"><a href="#">Placeholder</a></li>
</ul>
</header>
<div class="content">place holder</div>
</body>
</html>
```
```clojure
...
(defn my-nav-item [[caption func]]
(kioo/component "main.html" [:.nav-item]
{[:a] (do-> (content caption)
(set-attr :onClick func))}))
(defn my-header [heading nav-elms]
(kioo/component "main.html" [:header]
{[:h1] (content heading)
[:ul] (content (map my-nav-item nav-elms))}))
(defn my-page [data]
(kioo/component "main.html"
{[:header] (substitute (my-header (:heading data)
(:navigation data)))
[:.content] (content (:content data))}))
(def app-state (atom {:heading "main"
:content "Hello World"
:navigation [["home" #(js/alert %)]
["next" #(js/alert %)]]}))
(om/root app-state my-page (.-body js/document))
```
## Om
In an interview with David Nolen, Tom Coupland ([@tcoupland](https://twitter.com/tcoupland)) of InfoQ provides a nice summary of recent developments around Om ("[Om: Enhancing Facebook's React with Immutability](http://www.infoq.com/news/2014/01/om-react)").
> David [Nolen]: I think people are starting to see the limitations of just JavaScript and jQuery and even more structured solutions like Backbone, Angular, Ember, etc. React is a fresh approach to the DOM problem that seems obvious in hindsight.
>
> [Read the full interview...](http://www.infoq.com/news/2014/01/om-react)
### A slice of React, ClojureScript and Om
Fredrik Dyrkell ([@lexicallyscoped](https://twitter.com/lexicallyscoped)) rewrote part of the [React tutorial in both ClojureScript and Om](http://www.lexicallyscoped.com/2013/12/25/slice-of-reactjs-and-cljs.html), along with short, helpful explanations.
> React has sparked a lot of interest in the Clojure community lately [...]. At the very core, React lets you build up your DOM representation in a functional fashion by composing pure functions and you have a simple building block for everything: React components.
>
> [Read the full post...](http://www.lexicallyscoped.com/2013/12/25/slice-of-reactjs-and-cljs.html)
In a separate post, Dyrkell breaks down [how to build a binary clock component](http://www.lexicallyscoped.com/2014/01/23/ClojureScript-react-om-binary-clock.html) in Om.
[[Demo](http://www.lexicallyscoped.com/demo/binclock/)] [[Code](https://github.com/fredyr/binclock/blob/master/src/binclock/core.cljs)]
### Time Travel: Implementing undo in Om
David Nolen shows how to leverage immutable data structures to [add global undo](http://swannodette.github.io/2013/12/31/time-travel/) functionality to an app using just 13 lines of ClojureScript.
### A Step-by-Step Om Walkthrough
[Josh Lehman](http://www.joshlehman.me) took the time to create an extensive [step-by-step walkthrough](http://www.joshlehman.me/rewriting-the-react-tutorial-in-om/) of the React tutorial in Om. The well-documented source is on [github](https://github.com/jalehman/omtut-starter).
### Omkara
[brendanyounger](https://github.com/brendanyounger) created [omkara](https://github.com/brendanyounger/omkara), a starting point for ClojureScript web apps based on Om/React. It aims to take advantage of server-side rendering and comes with a few tips on getting started with Om/React projects.
### Om Experience Report
Adam Solove ([@asolove](https://twitter.com/asolove/)) [dives a little deeper into Om, React and ClojureScript](http://adamsolove.com/js/clojure/2014/01/06/om-experience-report.html). He shares some helpful tips he gathered while building his [CartoCrayon](https://github.com/asolove/carto-crayon) prototype.
## Not-so-random Tweet
<div><blockquote class="twitter-tweet" lang="en"><p>[@swannodette](https://twitter.com/swannodette) No thank you! It's honestly a bit weird because Om is exactly what I didn't know I wanted for doing functional UI work.</p>&mdash; Adam Solove (@asolove) <a href="https://twitter.com/asolove/status/420294067637858304">January 6, 2014</a></blockquote></div>

View File

@@ -0,0 +1,86 @@
---
title: "Community Round-up #16"
layout: post
author: Jonas Gebhardt
---
There have been many posts recently covering the <i>why</i> and <i>how</i> of React. This week's community round-up includes a collection of recent articles to help you get started with React, along with a few posts that explain some of the inner workings.
## React in a nutshell
Got five minutes to pitch React to your coworkers? John Lynch ([@johnrlynch](https://twitter.com/johnrlynch)) put together [this excellent and refreshing slideshow](http://slid.es/johnlynch/reactjs):
<iframe src="//slid.es/johnlynch/reactjs/embed" width="576" height="420" scrolling="no" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
## React's diff algorithm
React core team member Christopher Chedeau ([@vjeux](https://twitter.com/vjeux)) explores the innards of React's tree diffing algorithm in this [extensive and well-illustrated post](http://calendar.perfplanet.com/2013/diff/). <figure>[![](/react/img/blog/react-diff-tree.png)](http://calendar.perfplanet.com/2013/diff/)</figure>
While we're talking about tree diffing: Matt Esch ([@MatthewEsch](https://twitter.com/MatthewEsch)) created [this project](https://github.com/Matt-Esch/virtual-dom), which aims to implement the virtual DOM and a corresponding diff algorithm as separate modules.
## Many, many new introductions to React!
James Padosley wrote a short post on the basics (and merits) of React: [What is React?](http://james.padolsey.com/javascript/what-is-react/)
> What I like most about React is that it doesn't impose heady design patterns and data-modelling abstractions on me. [...] Its opinions are so minimal and its abstractions so focused on the problem of the DOM, that you can merrily slap your design choices atop.
> [Read the full post...](http://james.padolsey.com/javascript/what-is-react/)
Taylor Lapeyre ([@taylorlapeyre](https://twitter.com/taylorlapeyre)) wrote another nice [introduction to React](http://words.taylorlapeyre.me/an-introduction-to-react).
> React expects you to do the work of getting and pushing data from the server. This makes it very easy to implement React as a front end solution, since it simply expects you to hand it data. React does all the other work.
> [Read the full post...](http://words.taylorlapeyre.me/an-introduction-to-react)
[This "Deep explanation for newbies"](http://www.webdesignporto.com/react-js-in-pure-javascript-facebook-library/?utm_source=echojs&utm_medium=post&utm_campaign=echojs) by [@ProJavaScript](https://twitter.com/ProJavaScript) explains how to get started building a React game without using the optional JSX syntax.
### React around the world
It's great to see the React community expand internationally. [This site](http://habrahabr.ru/post/189230/) features a React introduction in Russian.
### React tutorial series
[Christopher Pitt](https://medium.com/@followchrisp) explains [React Components](https://medium.com/react-tutorials/828c397e3dc8) and [React Properties](https://medium.com/react-tutorials/ef11cd55caa0). The former includes a nice introduction to using JSX, while the latter focuses on adding interactivity and linking multiple components together. Also check out the [other posts in his React Tutorial series](https://medium.com/react-tutorials), e.g. on using [React + Backbone Model](https://medium.com/react-tutorials/8aaec65a546c) and [React + Backbone Router](https://medium.com/react-tutorials/c00be0cf1592).
### Beginner tutorial: Implementing the board game Go
[Chris LaRose](http://cjlarose.com/) walks through the steps of creating a Go app in React, showing how to separate application logic from the rendered components. Check out his [tutorial](http://cjlarose.com/2014/01/09/react-board-game-tutorial.html) or go straight to the [code](https://github.com/cjlarose/react-go).
### Egghead.io video tutorials
Joe Maddalone ([@joemaddalone](https://twitter.com/joemaddalone)) of [egghead.io](https://egghead.io/) created a series of React video tutorials, such as [this](http://www.youtube.com/watch?v=rFvZydtmsxM&feature=youtu.be&a) introduction to React Components. [[part 1](http://www.youtube.com/watch?v=rFvZydtmsxM&feature=youtu.be&a)], [[part 2](http://www.youtube.com/watch?v=5yvFLrt7N8M)]
### "React: Finally, a great server/client web stack"
Eric Florenzano ([@ericflo](https://twitter.com/ericflo)) sheds some light on what makes React perfect for server rendering:
> [...] the ideal solution would fully render the markup on the server, deliver it to the client so that it can be shown to the user instantly. Then it would asynchronously load some Javascript that would attach to the rendered markup, and invisibly promote the page into a full app that can render its own markup. [...]
> What I've discovered is that enough of the pieces have come together, that this futuristic-sounding web environment is actually surprisingly easy to do now with React.js.
> [Read the full post...](http://eflorenzano.com/blog/2014/01/23/react-finally-server-client/)
## Building a complex React component
[Matt Harrison](http://matt-harrison.com/) walks through the process of [creating an SVG-based Resistance Calculator](http://matt-harrison.com/building-a-complex-web-component-with-facebooks-react-library/) using React. <figure>[![](/react/img/blog/resistance-calculator.png)](http://matt-harrison.com/building-a-complex-web-component-with-facebooks-react-library/)</figure>
## Random Tweets
<div><blockquote class="twitter-tweet" lang="en"><p>[#reactjs](https://twitter.com/search?q=%23reactjs&src=hash) has very simple API, but it's amazing how much work has been done under the hood to make it blazing fast.</p>&mdash; Anton Astashov (@anton_astashov) <a href="https://twitter.com/anton_astashov/status/417556491646693378">December 30, 2013</a></blockquote></div>
<div><blockquote class="twitter-tweet" lang="en"><p>[#reactjs]((https://twitter.com/search?q=%23reactjs&src=hash) makes refactoring your HTML as easy & natural as refactoring your javascript [@react_js](https://twitter.com/react_js)</p>&mdash; Jared Forsyth (@jaredforsyth) <a href="https://twitter.com/jaredforsyth/status/420304083010854912">January 6, 2014</a></blockquote></div>
<div><blockquote class="twitter-tweet" lang="en"><p>Played with react.js for an hour, so many things suddenly became stupidly simple.</p>&mdash; andrewingram (@andrewingram) <a href="https://twitter.com/andrewingram/status/422810480701620225">January 13, 2014</a></blockquote></div>
<div><blockquote class="twitter-tweet" lang="en"><p>[@okonetchnikov](https://twitter.com/okonetchnikov) HOLY CRAP react is nice</p>&mdash; julik (@julikt) <a href="https://twitter.com/julikt/status/422843478792765440">January 13, 2014</a></blockquote></div>
<div><blockquote class="twitter-tweet" lang="en"><p>brb rewriting everything with react
</p>&mdash; Ben Smithett (@bensmithett) <a href="https://twitter.com/bensmithett/status/430671242186592256">February 4, 2014</a></blockquote></div>

View File

@@ -0,0 +1,132 @@
---
title: React v0.9 RC
layout: post
author: Ben Alpert
---
We're almost ready to release React v0.9! We're posting a release candidate so that you can test your apps on it; we'd much prefer to find show-stopping bugs now rather than after we release.
The release candidate is available for download from the CDN:
* **React**
Dev build with warnings: <http://fb.me/react-0.9.0-rc1.js>
Minified build for production: <http://fb.me/react-0.9.0-rc1.min.js>
* **React with Add-Ons**
Dev build with warnings: <http://fb.me/react-with-addons-0.9.0-rc1.js>
Minified build for production: <http://fb.me/react-with-addons-0.9.0-rc1.min.js>
* **In-Browser JSX transformer**
<http://fb.me/JSXTransformer-0.9.0-rc1.js>
We've also published version `0.9.0-rc1` of the `react` and `react-tools` packages on npm and the `react` package on bower.
Please try these builds out and [file an issue on GitHub](https://github.com/facebook/react/issues/new) if you see anything awry.
## Upgrade Notes
In addition to the changes to React core listed below, we've made a small change to the way JSX interprets whitespace to make things more consistent. With this release, space between two components on the same line will be preserved, while a newline separating a text node from a tag will be eliminated in the output. Consider the code:
```html
<div>
Monkeys:
{listOfMonkeys} {submitButton}
</div>
```
In v0.8 and below, it was transformed to the following:
```javascript
React.DOM.div(null,
" Monkeys: ",
listOfMonkeys, submitButton
)
```
In v0.9, it will be transformed to this JS instead:
```javascript{2,3}
React.DOM.div(null,
"Monkeys:",
listOfMonkeys, " ", submitButton
)
```
We believe this new behavior is more helpful and elimates cases where unwanted whitespace was previously added.
In cases where you want to preserve the space adjacent to a newline, you can write a JS string like `{"Monkeys: "}` in your JSX source. We've included a script to do an automated codemod of your JSX source tree that preserves the old whitespace behavior by adding and removing spaces appropriately. You can [install jsx\_whitespace\_transformer from npm](https://github.com/facebook/react/blob/master/npm-jsx_whitespace_transformer/README.md) and run it over your source tree to modify files in place. The transformed JSX files will preserve your code's existing whitespace behavior.
## Changelog
### React Core
#### Breaking Changes
- The lifecycle methods `componentDidMount` and `componentDidUpdate` no longer receive the root node as a parameter; use `this.getDOMNode()` instead
- Whenever a prop is equal to `undefined`, the default value returned by `getDefaultProps` will now be used instead
- `React.unmountAndReleaseReactRootNode` was previously deprecated and has now been removed
- `React.renderComponentToString` is now synchronous and returns the generated HTML string
- Full-page rendering (that is, rendering the `<html>` tag using React) is now supported only when starting with server-rendered markup
- On mouse wheel events, `deltaY` is no longer negated
- When prop types validation fails, a warning is logged instead of an error thrown (with the production build of React, the type checks are now skipped for performance)
- On `input`, `select`, and `textarea` elements, `.getValue()` is no longer supported; use `.getDOMNode().value` instead
#### New Features
- React now never rethrows errors, so stack traces are more accurate and Chrome's purple break-on-error stop sign now works properly
- Added a new tool for profiling React components and identifying places where defining `shouldComponentUpdate` can give performance improvements
- Added support for SVG tags `defs`, `linearGradient`, `polygon`, `radialGradient`, `stop`
- Added support for more attributes:
- `noValidate` and `formNoValidate` for forms
- `property` for Open Graph `<meta>` tags
- `sandbox`, `seamless`, and `srcDoc` for `<iframe>` tags
- `scope` for screen readers
- `span` for `<colgroup>` tags
- Added support for defining `propTypes` in mixins
- Added `any`, `arrayOf`, `component`, `oneOfType`, `renderable`, `shape` to `React.PropTypes`
- Added support for `statics` on component spec for static component methods
- On all events, `.currentTarget` is now properly set
- On keyboard events, `.key` is now polyfilled in all browsers for special (non-printable) keys
- On clipboard events, `.clipboardData` is now polyfilled in IE
- On drag events, `.dragTransfer` is now present
- Added support for `onMouseOver` and `onMouseOut` in addition to the existing `onMouseEnter` and `onMouseLeave` events
- Added support for `onLoad` and `onError` on `<img>` elements
- Added support for `onReset` on `<form>` elements
- The `autoFocus` attribute is now polyfilled consistently on `input`, `select`, and `textarea`
#### Bug Fixes
- React no longer adds an `__owner__` property to each component's `props` object; passed-in props are now never mutated
- When nesting top-level components (e.g., calling `React.renderComponent` within `componentDidMount`), events now properly bubble to the parent component
- Fixed a case where nesting top-level components would throw an error when updating
- Passing an invalid or misspelled propTypes type now throws an error
- On mouse enter/leave events, `.target`, `.relatedTarget`, and `.type` are now set properly
- On composition events, `.data` is now properly normalized in IE9 and IE10
- CSS property values no longer have `px` appended for the unitless properties `columnCount`, `flex`, `flexGrow`, `flexShrink`, `lineClamp`, `order`, `widows`
- Fixed a memory leak when unmounting children with a `componentWillUnmount` handler
- Fixed a memory leak when `renderComponentToString` would store event handlers
- Fixed an error that could be thrown when removing form elements during a click handler
- `key` values containing `.` are now supported
- Shortened `data-reactid` values for performance
- Components now always remount when the `key` property changes
- Event handlers are attached to `document` only when necessary, improving performance in some cases
- Events no longer use `.returnValue` in modern browsers, eliminating a warning in Chrome
- `scrollLeft` and `scrollTop` are no longer accessed on document.body, eliminating a warning in Chrome
- General performance fixes, memory optimizations, improvements to warnings and error messages
### React with Addons
- `React.addons.TransitionGroup` was renamed to `React.addons.CSSTransitionGroup`
- `React.addons.TransitionGroup` was added as a more general animation wrapper
- `React.addons.cloneWithProps` was added for cloning components and modifying their props
- Bug fix for adding back nodes during an exit transition for CSSTransitionGroup
- Bug fix for changing `transitionLeave` in CSSTransitionGroup
- Performance optimizations for CSSTransitionGroup
- On checkbox `<input>` elements, `checkedLink` is now supported for two-way binding
### JSX Compiler and react-tools Package
- Whitespace normalization has changed; now space between two tags on the same line will be preserved, while newlines between two tags will be removed
- The `react-tools` npm package no longer includes the React core libraries; use the `react` package instead.
- `displayName` is now added in more cases, improving error messages and names in the React Dev Tools
- Fixed an issue where an invalid token error was thrown after a JSX closing tag
- `JSXTransformer` now uses source maps automatically in modern browsers
- `JSXTransformer` error messages now include the filename and problematic line contents when a file fails to parse

View File

@@ -20,12 +20,12 @@ sectionid: blog
<div class="pagination">
{% if paginator.previous_page %}
<a href="/react/blog/{{ paginator.previous_page_path }}" class="previous">
<a href="/react/{{ paginator.previous_page_path }}" class="previous">
&laquo; Previous Page
</a>
{% endif %}
{% if paginator.next_page %}
<a href="/react/blog/{{ paginator.next_page_path }}" class="next">
<a href="/react{{ paginator.next_page_path }}" class="next">
Next Page &raquo;
</a>
{% endif %}

View File

@@ -19,7 +19,7 @@ Let's look at a really simple example. Create a `hello-react.html` file with the
<html>
<head>
<title>Hello React</title>
<script src="http://fb.me/react-{{site.react_version}}.min.js"></script>
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
</head>
<body>
@@ -84,8 +84,8 @@ We've found that the best solution for this problem is to generate markup direct
**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.**
JSX is very small; the "hello, world" example above uses every feature of JSX. To learn more about it, see [JSX in depth](./jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
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).
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](./jsx-gotchas.html) for some key differences.
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.

View File

@@ -10,6 +10,11 @@ next: jsx-gotchas.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.
## Why JSX?
@@ -53,9 +58,11 @@ var app = Nav({color:"blue"}, Profile(null, "click"));
```
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
desugars into native JavaScript.
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](getting-started.html) guide shows
If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows
how to setup compilation.
> Note:
@@ -92,7 +99,10 @@ var MyComponent = React.createClass({/*...*/});
var app = <MyComponent someProperty={true} />;
```
See [Multiple Components](multiple-components.html) to learn more about using composite components.
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.
> Note:
>
@@ -157,19 +167,6 @@ It's easy to add comments within your JSX; they're just JS expressions:
var content = <Container>{/* this is a comment */}<Nav /></Container>;
```
## Tooling
Beyond the compilation step, JSX does not require any special tools.
* Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
* JSX syntax highlighting is available for Sublime Text and other editors
that support `*.tmLanguage` using the third-party
[`JavaScript (JSX).tmLanguage`][1].
* Linting provides accurate line numbers after compiling without sourcemaps.
* Elements use standard scoping so linters can find usage of out-of-scope
components.
[1]: https://github.com/yungsters/sublime/blob/master/tmLanguage/JavaScript%20(JSX).tmLanguage
## Prior Work
@@ -181,4 +178,4 @@ efforts include:
* 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](./jsx-gotchas.html) for some key differences.
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.

View File

@@ -11,7 +11,7 @@ JSX looks like HTML but there are some important differences you may run into.
> Note:
>
> For DOM differences, such as the inline `style` attribute, check [here](dom-differences.html).
> For DOM differences, such as the inline `style` attribute, check [here](/react/docs/dom-differences.html).
## Whitespace Removal

View File

@@ -7,7 +7,7 @@ prev: jsx-gotchas.html
next: multiple-components.html
---
You've already [learned how to display data](./displaying-data.html) with React. Now let's look at how to make our UIs interactive.
You've already [learned how to display data](/react/docs/displaying-data.html) with React. Now let's look at how to make our UIs interactive.
## A Simple Example
@@ -46,7 +46,7 @@ With React you simply pass your event handler as a camelCased prop similar to ho
If you'd like to use React on a touch device (i.e. a phone or tablet), simply call `React.initializeTouchEvents(true);` to turn them on.
## Under the Hood: autoBind and Event Delegation
## Under the Hood: Autobinding and Event Delegation
Under the hood React does a few things to keep your code performant and easy to understand.

View File

@@ -144,7 +144,7 @@ In React, data flows from owner to owned component through `props` as discussed
You may be thinking that it's expensive to react to changing data if there are a large number of nodes under an owner. The good news is that JavaScript is fast and `render()` methods tend to be quite simple, so in most applications this is extremely fast. Additionally, the bottleneck is almost always the DOM mutation and not JS execution and React will optimize this for you using batching and change detection.
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](component-specs.html) for more information.
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](/react/docs/component-specs.html) for more information.
> Note:
>

View File

@@ -96,7 +96,7 @@ React.renderComponent(
Components are the best way to reuse code in React, but sometimes very different components may share some common functionality. These are sometimes called [cross-cutting concerns](http://en.wikipedia.org/wiki/Cross-cutting_concern). React provides `mixins` to solve this problem.
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](./working-with-the-browser.html) 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.
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 */

View File

@@ -87,7 +87,7 @@ If you want to initialize the component with a non-empty value, you can supply a
This example will function much like the **Controlled Components** example above.
Likewise, `<input>` supports `defaultChecked` and `<option>` supports `defaultSelected`.
Likewise, `<input>` supports `defaultChecked` and `<select>` supports `defaultValue`.
## Advanced Topics
@@ -130,3 +130,18 @@ For HTML, this easily allows developers to supply multiline values. However, sin
```
If you *do* decide to use children, they will behave like `defaultValue`.
### Why Select Value?
The selected `<option>` in an HTML `<select>` is normally specified through that option's `selected` attribute. In React, in order to make components easier to manipulate, the following format is adopted instead:
```javascript
<select value="B">
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
```
To make an uncontrolled component, `defaultValue` is used instead.

View File

@@ -10,7 +10,7 @@ next: more-about-refs.html
React provides powerful abstractions that free you from touching the DOM directly in most cases, but sometimes you simply need to access the underlying API, perhaps to work with a third-party library or existing code.
## The Mock DOM
## The Virtual DOM
React is so fast because it never talks to the DOM directly. React maintains a fast in-memory representation of the DOM. `render()` methods return a *description* of the DOM, and React can diff this description with the in-memory representation to compute the fastest way to update the browser.
@@ -62,7 +62,7 @@ React.renderComponent(
## More About Refs
To learn more about refs, including ways to use them effectively, see our [more about refs](./more-about-refs.html) documentation.
To learn more about refs, including ways to use them effectively, see our [more about refs](/react/docs/more-about-refs.html) documentation.
## Component Lifecycle
@@ -119,7 +119,7 @@ In addition to that philosophy, we've also taken the stance that we, as authors
### Polyfills Needed to Support Older Browsers
These six functions can be polyfilled using `es5-shim.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim):
`es5-shim.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim) provides the following that React needs:
* `Array.isArray`
* `Array.prototype.forEach`
@@ -128,7 +128,23 @@ These six functions can be polyfilled using `es5-shim.js` from [kriskowal's es5-
* `Date.now`
* `Function.prototype.bind`
Other required polyfills:
`es5-sham.js`, also from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim), provides the following that React needs:
* `Object.create` Provided by `es5-sham.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim).
* `console.*` Only needed when using the unminified build. If you need to polyfill this, try [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).
* `Object.create`
The unminified build of React needs the following from [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).
* `console.*`
### Cross-browser Issues
Although React is pretty good at abstracting browser differences, some browsers are limited or present quirky behaviors that we couldn't find a workaround.
#### onScroll event on IE8
On IE8 the `onScroll` event doesn't bubble and IE8 doesn't have an API to define handlers to the capturing phase of an event, meaning there is no way for React to listen to these events.
Currently a handler to this event is ignored on IE8.
See the [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) GitHub issue for more information.

View File

@@ -42,11 +42,16 @@ The open-source community has built tools that integrate JSX with several build
* [reactify](https://github.com/andreypopp/reactify) - use JSX with [browserify](http://browserify.org/)
* [grunt-react](https://github.com/ericclemmons/grunt-react) - [grunt](http://gruntjs.com/) task for JSX
* [require-jsx](https://github.com/seiffert/require-jsx) - use JSX with [require.js](http://requirejs.org/)
* [gulp-react](https://github.com/sindresorhus/gulp-react) - [gulp](http://gulpjs.com/) task for JSX
* [jsx-requirejs-plugin](https://github.com/philix/jsx-requirejs-plugin) - use JSX with [require.js](http://requirejs.org/) and precompile JSX files with r.js
* [pyReact](https://github.com/facebook/react-python) - use JSX with [Python](http://www.python.org/)
* [react-rails](https://github.com/facebook/react-rails) - use JSX with [Ruby on Rails](http://rubyonrails.org/)
## React Page
### Syntax Highlighting & Linting
To get started on a new project, you can use [react-page](https://github.com/facebook/react-page/), a complete React project creator. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
* Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
* [JSX syntax highlighting](https://github.com/yungsters/sublime/blob/master/tmLanguage/JavaScript%20(JSX\).tmLanguage) is available for Sublime Text and other editors
that support `*.tmLanguage`.
* Linting provides accurate line numbers after compiling without sourcemaps.
* Elements use standard scoping so linters can find usage of out-of-scope components.

View File

@@ -4,207 +4,13 @@ title: Add-ons
layout: docs
permalink: addons.html
prev: tooling-integration.html
next: examples.html
next: animation.html
---
`React.addons` is where we park some useful utilities for building React apps. **These should be considered experimental** but will eventually be rolled into core or a blessed utilities library.
`React.addons` is where we park some useful utilities for building React apps. **These should be considered experimental** but will eventually be rolled into core or a blessed utilities library:
## CSS Animation and Transitions
- `ReactTransitions`, for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal.
- `ReactLink`, to simplify the coordination between user's form input data and and the component's state.
- `classSet`, for manipulating the DOM `class` string a bit more cleanly.
`ReactTransitions` is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM. `ReactTransitions` is inspired by the excellent [ng-animate](http://www.nganimate.org/) library.
### Getting Started
`ReactTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out.
```javascript{22-24}
/** @jsx React.DOM */
var ReactTransitionGroup = React.addons.TransitionGroup;
var TodoList = React.createClass({
getInitialState: function() {
return {items: ['hello', 'world', 'click', 'me']};
},
handleAdd: function() {
var newItems =
this.state.items.concat([prompt('Enter some text')]);
this.setState({items: newItems});
},
handleRemove: function(i) {
var newItems = this.state.items;
newItems.splice(i, 0)
this.setState({items: newItems});
},
render: function() {
var items = this.state.items.map(function(item, i) {
return (
<div key={i} onClick={this.handleRemove.bind(this, i)}>
{item}}
</div>
);
}.bind(this));
return (
<div>
<div><button onClick={this.handleAdd} /></div>
<ReactTransitionGroup transitionName="example">
{items}
</ReactTransitionGroup>
</div>
);
}
});
```
In this component, when a new item is added `ReactTransitionGroup` it will get the `example-enter` CSS class and the `example-enter-active` CSS class added in the next tick. This is a convention based on the `transitionName` prop.
You can use these classes to trigger a CSS animation or transition. For example, try adding this CSS and adding a new list item:
```css
.example-enter {
opacity: 0.01;
transition: opacity .5s ease-in;
}
.example-enter.example-enter-active {
opacity: 0.99;
}
```
You'll notice that when you try to remove an item `ReactTransitionGroup` keeps it in the DOM. If you're using an unminified build of React you'll see a warning that React was expecting an animation or transition to occur. That's because `ReactTransitionGroup` keeps your DOM elements on the page until the animation completes. Try adding this CSS:
```css
.example-leave {
opacity: 0.99;
transition: opacity .5s ease-in;
}
.example-leave.example-leave-active {
opacity: 0.01;
}
```
### Disabling Animations
You can disable animating `enter` or `leave` animations if you want. For example, sometimes you may want an `enter` animation and no `leave` animation, but `ReactTransitionGroup` waits for an animation to complete before removing your DOM node. You can add `transitionEnter={false}` or `transitionLeave={false}` props to `ReactTransitionGroup` to disable these animations.
### Rendering a Different Component
By default `ReactTransitionGroup` renders as a `span`. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`:
```javascript{3}
<ReactTransitionGroup
transitionName="example"
component={React.DOM.ul}>
...
</ReactTransitionGroup>
```
`component` does not need to be a DOM component. It can be any component you want; even one you've written yourself!
## ReactLink
`ReactLink` is an easy way to express two-way binding with React.
In React, data flows one way: from owner to child. This is because data only flows one direction in [the Von Neumann model of computing](http://en.wikipedia.org/wiki/Von_Neumann_architecture). You can think of it as "one-way data binding."
However, there are lots of applications that require you to read some data and flow it back into your program. For example, when developing forms, you'll often want to update some React `state` when you receive user input. Or perhaps you want to perform layout in JavaScript and react to changes in some DOM element size.
In React, you would implement this by listening to a "change" event, read from your data source (usually the DOM) and call `setState()` on one of your components. "Closing the data flow loop" explicitly leads to more understandable and easier-to-maintain programs. See [our forms documentation](./forms.html) for more information.
Two-way binding -- implicitly enforcing that some value in the DOM is always consistent with some React `state` -- is concise and supports a wide variety of applications. We've provided `ReactLink`: syntactic sugar for setting up the common data flow loop pattern described above, or "linking" some data source to React `state`.
> Note:
>
> ReactLink is just a thin wrapper and convention around the `onChange`/`setState()` pattern. It doesn't fundamentally change how data flows in your React application.
### ReactLink: Before and After
Here's a simple form example without using `ReactLink`:
```javascript
/** @jsx React.DOM */
var NoLink = React.createClass({
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
var value = this.state.value;
return <input type="text" value={value} onChange={this.handleChange} />;
}
});
```
This works really well and it's very clear how data is flowing, however with a lot of form fields it could get a bit verbose. Let's use `ReactLink` to save us some typing:
```javascript{4,9}
/** @jsx React.DOM */
var WithLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {value: 'Hello!'};
},
render: function() {
return <input type="text" valueLink={this.linkState('value')} />;
}
});
```
`LinkedStateMixin` adds a method ot your React component called `linkState()`. `linkState()` returns a `ReactLink` object which contains the current value of the React state and a callback to change it.
`ReactLink` objects can be passed up and down the tree as props, so it's easy (and explicit) to set up two-way binding between a component deep in the hierarchy and state that lives higher in the hierarchy.
### Under the Hood
There are two sides to `ReactLink`: the place where you create the `ReactLink` instance and the place where you use it. To prove how simple `ReactLink` is, let's rewrite each side separately to be more explicit.
#### ReactLink Without LinkedStateMixin
```javascript{7-9,11-14}
/** @jsx React.DOM */
var WithoutMixin = React.createClass({
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(newValue) {
this.setState({value: newValue});
},
render: function() {
var valueLink = {
value: this.state.value,
requestChange: this.handleChange
};
return <input type="text" valueLink={valueLink} />;
}
});
```
As you can see, `ReactLink` objects are very simple objects that just have a `value` and `requestChange` prop. And `LinkedStateMixin` is similarly simple: it just populates those fields with a value from `this.state` and a callback that calls `this.setState()`.
#### ReactLink Without valueLink
```javascript
/** @jsx React.DOM */
var WithoutLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {value: 'Hello!'};
},
render: function() {
var valueLink = this.linkState('value');
var handleChange = function(e) {
valueLink.requestChange(e.target.value);
};
return <input type="text" value={valueLink.value} onChange={handleChange} />;
}
});
```
The `valueLink` prop is also quite simple. It simply handles the `onChange` event and calls `this.props.valueLink.requestChange()` and also uses `this.props.valueLink.value` instead of `this.props.value`. That's it!
To get the add-ons, use `react-with-addons.js` (and its minified counterpart) rather than the common `react.js`.

View File

@@ -0,0 +1,99 @@
---
id: animation
title: Animation
layout: docs
permalink: animation.html
prev: addons.html
next: two-way-binding-helpers.html
---
`ReactTransitions` is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM. It's inspired by the excellent [ng-animate](http://www.nganimate.org/) library.
## Getting Started
`ReactTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out.
```javascript{22-24}
/** @jsx React.DOM */
var ReactTransitionGroup = React.addons.TransitionGroup;
var TodoList = React.createClass({
getInitialState: function() {
return {items: ['hello', 'world', 'click', 'me']};
},
handleAdd: function() {
var newItems =
this.state.items.concat([prompt('Enter some text')]);
this.setState({items: newItems});
},
handleRemove: function(i) {
var newItems = this.state.items;
newItems.splice(i, 1)
this.setState({items: newItems});
},
render: function() {
var items = this.state.items.map(function(item, i) {
return (
<div key={item} onClick={this.handleRemove.bind(this, i)}>
{item}
</div>
);
}.bind(this));
return (
<div>
<div><button onClick={this.handleAdd} /></div>
<ReactTransitionGroup transitionName="example">
{items}
</ReactTransitionGroup>
</div>
);
}
});
```
In this component, when a new item is added to `ReactTransitionGroup` it will get the `example-enter` CSS class and the `example-enter-active` CSS class added in the next tick. This is a convention based on the `transitionName` prop.
You can use these classes to trigger a CSS animation or transition. For example, try adding this CSS and adding a new list item:
```css
.example-enter {
opacity: 0.01;
transition: opacity .5s ease-in;
}
.example-enter.example-enter-active {
opacity: 1;
}
```
You'll notice that when you try to remove an item `ReactTransitionGroup` keeps it in the DOM. If you're using an unminified build of React with add-ons you'll see a warning that React was expecting an animation or transition to occur. That's because `ReactTransitionGroup` keeps your DOM elements on the page until the animation completes. Try adding this CSS:
```css
.example-leave {
opacity: 1;
transition: opacity .5s ease-in;
}
.example-leave.example-leave-active {
opacity: 0.01;
}
```
## Disabling Animations
You can disable animating `enter` or `leave` animations if you want. For example, sometimes you may want an `enter` animation and no `leave` animation, but `ReactTransitionGroup` waits for an animation to complete before removing your DOM node. You can add `transitionEnter={false}` or `transitionLeave={false}` props to `ReactTransitionGroup` to disable these animations.
## Rendering a Different Component
By default `ReactTransitionGroup` renders as a `span`. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`:
```javascript{3}
<ReactTransitionGroup
transitionName="example"
component={React.DOM.ul}>
...
</ReactTransitionGroup>
```
Every DOM component is under `React.DOM`. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself!

View File

@@ -0,0 +1,117 @@
---
id: two-way-binding-helpers
title: Two-Way Binding Helpers
layout: docs
permalink: two-way-binding-helpers.html
prev: animation.html
next: class-name-manipulation.html
---
`ReactLink` is an easy way to express two-way binding with React.
> Note:
>
> If you're new to the framework, note that `ReactLink` is not needed for most applications and should be used cautiously.
In React, data flows one way: from owner to child. This is because data only flows one direction in [the Von Neumann model of computing](http://en.wikipedia.org/wiki/Von_Neumann_architecture). You can think of it as "one-way data binding."
However, there are lots of applications that require you to read some data and flow it back into your program. For example, when developing forms, you'll often want to update some React `state` when you receive user input. Or perhaps you want to perform layout in JavaScript and react to changes in some DOM element size.
In React, you would implement this by listening to a "change" event, read from your data source (usually the DOM) and call `setState()` on one of your components. "Closing the data flow loop" explicitly leads to more understandable and easier-to-maintain programs. See [our forms documentation](/react/docs/forms.html) for more information.
Two-way binding -- implicitly enforcing that some value in the DOM is always consistent with some React `state` -- is concise and supports a wide variety of applications. We've provided `ReactLink`: syntactic sugar for setting up the common data flow loop pattern described above, or "linking" some data source to React `state`.
> Note:
>
> ReactLink is just a thin wrapper and convention around the `onChange`/`setState()` pattern. It doesn't fundamentally change how data flows in your React application.
## ReactLink: Before and After
Here's a simple form example without using `ReactLink`:
```javascript
/** @jsx React.DOM */
var NoLink = React.createClass({
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
var value = this.state.value;
return <input type="text" value={value} onChange={this.handleChange} />;
}
});
```
This works really well and it's very clear how data is flowing, however with a lot of form fields it could get a bit verbose. Let's use `ReactLink` to save us some typing:
```javascript{4,9}
/** @jsx React.DOM */
var WithLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {value: 'Hello!'};
},
render: function() {
return <input type="text" valueLink={this.linkState('value')} />;
}
});
```
`LinkedStateMixin` adds a method to your React component called `linkState()`. `linkState()` returns a `ReactLink` object which contains the current value of the React state and a callback to change it.
`ReactLink` objects can be passed up and down the tree as props, so it's easy (and explicit) to set up two-way binding between a component deep in the hierarchy and state that lives higher in the hierarchy.
## Under the Hood
There are two sides to `ReactLink`: the place where you create the `ReactLink` instance and the place where you use it. To prove how simple `ReactLink` is, let's rewrite each side separately to be more explicit.
### ReactLink Without LinkedStateMixin
```javascript{7-9,11-14}
/** @jsx React.DOM */
var WithoutMixin = React.createClass({
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(newValue) {
this.setState({value: newValue});
},
render: function() {
var valueLink = {
value: this.state.value,
requestChange: this.handleChange
};
return <input type="text" valueLink={valueLink} />;
}
});
```
As you can see, `ReactLink` objects are very simple objects that just have a `value` and `requestChange` prop. And `LinkedStateMixin` is similarly simple: it just populates those fields with a value from `this.state` and a callback that calls `this.setState()`.
### ReactLink Without valueLink
```javascript
/** @jsx React.DOM */
var WithoutLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {value: 'Hello!'};
},
render: function() {
var valueLink = this.linkState('value');
var handleChange = function(e) {
valueLink.requestChange(e.target.value);
};
return <input type="text" value={valueLink.value} onChange={handleChange} />;
}
});
```
The `valueLink` prop is also quite simple. It simply handles the `onChange` event and calls `this.props.valueLink.requestChange()` and also uses `this.props.valueLink.value` instead of `this.props.value`. That's it!

View File

@@ -0,0 +1,46 @@
---
id: class-name-manipulation
title: Class Name Manipulation
layout: docs
permalink: class-name-manipulation.html
prev: two-way-binding-helpers.html
next: examples.html
---
`classSet()` is a neat utility for easily manipulating the DOM `class` string.
Here's a common scenario and its solution without `classSet()`:
```javascript
// inside some `<Message />` React component
render: function() {
var classString = 'message';
if (this.props.isImportant) {
classString += ' message-important';
}
if (this.props.isRead) {
classString += ' message-read';
}
// 'message message-important message-read'
return <div className={classString}>Great, I'll be there.</div>;
}
```
This can quickly get tedious, as assigning class name strings can be hard to read and error-prone. `classSet()` solves this problem:
```javascript
render: function() {
var cx = React.addons.classSet;
var classes = cx({
'message': true,
'message-important': this.props.isImportant,
'message-read': this.props.isRead
});
// same final string, but much cleaner
return <div className={classes}>Great, I'll be there.</div>;
}
```
When using `classSet()`, pass an object with keys of the CSS class names you might or might not need. Truthy values will result in the key being a part of the resulting string.
No more hacky string concatenations!

View File

@@ -3,7 +3,7 @@ id: examples
title: Examples
layout: docs
permalink: examples.html
prev: addons.html
prev: class-name-manipulation.html
---
### Production Apps
@@ -15,8 +15,7 @@ prev: addons.html
### Sample Code
* We've included [a step-by-step comment box tutorial](./tutorial.html).
* We've included [a step-by-step comment box tutorial](/react/docs/tutorial.html).
* [The React starter kit](/react/downloads.html) includes several examples which you can [view online in our GitHub repository](https://github.com/facebook/react/tree/master/examples/).
* [React Page](https://github.com/facebook/react-page) is a simple React project creator to get you up-and-running quickly with React. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
* [React one-hour email](https://github.com/petehunt/react-one-hour-email/commits/master) goes step-by-step from a static HTML mock to an interactive email reader (written in just one hour!)
* [Rendr + React app template](https://github.com/petehunt/rendr-react-template/) demonstrates how to use React's server rendering capabilities.

View File

@@ -1,96 +0,0 @@
---
id: OUTLINE
title: Goals of the documentation
layout: docs
prev: 09.1-tutorial.html
---
- Flow of docs should mimic progression of questions a new user would ask
- High information density -- assume the reader is adept at JS
- Talk about best practices
- JSFiddles for all code samples
- Provide background for some of the design decisions
- Less words less words less words!
## Outline
Motivation / Why React?
- Declarative (simple)
- Components (separation of concerns)
- Give it 5 minutes
Displaying data
- Hello world example
- Reactive updates
- Components are just functions
- JSX syntax (link to separate doc?)
- JSX gotchas
Interactivity and dynamic UIs
- Click handler example
- Event handlers / synthetic events (link to w3c docs)
- Under the hood: autoBind and event delegation (IE8 notes)
- React is a state machine
- How state works
- What components should have state?
- What should go in state?
- What shouldn't go in state?
Scaling up: using multiple components
- Motivation: separate concerns
- Composition example
- Ownership (and owner vs. parent)
- Children
- Data flow (one-way data binding)
- A note on performance
Building effective reusable components
- You should build a reusable component library (CSS, testing etc)
- Prop validation
- Transferring props: a shortcut
- Mixins
- Testing
Forms
Working with the browser
- The mock DOM
- Refs / getDOMNode()
- More about refs
- Component lifecycle
- Browser support and polyfills
Working with your environment
- CDN-hosted React
- Using master
- In-browser JSX transform
- Productionizing: precompiled JSX
- Helpful open-source projects
Integrating with other UI libraries
- Using jQuery plugins
- Letting jQuery manage React components
- Using with Backbone.View
- CoffeeScript
- Moving from Handlebars to React: an example
Server / static rendering
- Motivation
- Simple example
- How does it work? (No DOM)
- Rendr + React
Big ideas
- Animation
- Bootstrap bindings (responsive grids)
- Reactive CSS
- Web workers
- Native views
Case studies
- Comment box tutorial from scratch
- From HTML mock to application: React one-hour email
- Jordan's LikeToggler example
Reference
- API
- DOM differences

View File

@@ -0,0 +1,46 @@
---
id: complementary-tools
title: Complementary Tools
layout: docs
permalink: complementary-tools.html
prev: videos.html
next: example-apps.html
---
React is a small library that does one thing well. Here's a list of tools we've found that work really well with React when building applications.
If you want your project on this list, or think one of these projects should be removed, [open an issue on GitHub](https://github.com/facebook/react/issues/new).
### JSX integrations
* **[jsxhint](https://npmjs.org/package/jsxhint)** [JSHint](http://jshint.com/) (linting) support
* **[reactify](https://npmjs.org/package/reactify)** [Browserify](http://browserify.org/) transform
* **[node-jsx](https://npmjs.org/package/node-jsx)** Native [Node](http://nodejs.org/) support
* **[jsx-loader](https://npmjs.org/package/jsx-loader)** Loader for [webpack](http://webpack.github.io/)
* **[grunt-react](https://npmjs.org/package/grunt-react)** [GruntJS](http://gruntjs.com/) task
* **[gulp-react](https://npmjs.org/package/gulp-react)** [GulpJS](http://gulpjs.com/) plugin
* **[jsx-requirejs-plugin](https://github.com/philix/jsx-requirejs-plugin)** [RequireJS](http://requirejs.org/) plugin
### Full-stack starter kits
* **[react-app](https://github.com/andreypopp/react-app)** Rapid appliaction development with React with server rendering
* **[generator-react-webpack](https://github.com/newtriks/generator-react-webpack)** [Yeoman](http://yeoman.io/) generator for React and Webpack
* **[Genesis Skeleton](http://genesis-skeleton.com/)** Modern, opinionated, full-stack starter kit for rapid, streamlined application development (supports React)
* **[react-starter-template](https://github.com/johnthethird/react-starter-template)** Starter template with Gulp, Webpack and Bootstrap
* **[react-brunch](https://npmjs.org/package/react-brunch)** [Brunch](http://brunch.io/) plugin
* **[react-browserify-template](https://github.com/petehunt/react-browserify-template)** Quick-start with Browserify
### Routing
* **[director](https://github.com/flatiron/director)** (for an example see [TodoMVC](https://github.com/tastejs/todomvc/blob/gh-pages/architecture-examples/react/js/app.jsx#L29))
* **[Backbone](https://backbonejs.org/)** (for an example see [github-issues-viewer](https://github.com/jaredly/github-issues-viewer))
### Model management
* **[react.backbone](https://github.com/usepropeller/react.backbone)** Use [Backbone](http://backbonejs.org) models with React
* **[cortex](https://github.com/mquan/cortex/)** A JavaScript library for centrally managing data with React
### UI components
* **[react-bootstrap](https://github.com/stevoland/react-bootstrap)** Bootstrap 3 components built with React
* **[react-topcoat](https://github.com/plaxdan/react-topcoat)** Topcoat components built with React

14
docs/docs/example-apps.md Normal file
View File

@@ -0,0 +1,14 @@
---
id: example-apps
title: Example apps
layout: docs
permalink: example-apps.html
prev: complementary-tools.html
---
Here is a selection of open-source apps built with React.
* **[TodoMVC](https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/react/js)**
* **[Khan Academy question editor](https://github.com/khan/perseus)** (browse their GitHub account for many more production apps!)
* **[github-issues-viewer](https://github.com/jaredly/github-issues-viewer)**
* **[hn-react](https://github.com/prabirshrestha/hn-react)** Dead-simple Hacker News client in React

View File

@@ -28,7 +28,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
<!DOCTYPE html>
<html>
<head>
<script src="build/react.min.js"></script>
<script src="build/react.js"></script>
<script src="build/JSXTransformer.js"></script>
</head>
<body>
@@ -44,7 +44,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
</html>
```
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](/react/docs/jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
### Separate File
@@ -90,7 +90,7 @@ React.renderComponent(
> Note:
>
> 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.
> 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.
Update your HTML file as below:
@@ -99,7 +99,7 @@ Update your HTML file as below:
<html>
<head>
<title>Hello React!</title>
<script src="build/react.min.js"></script>
<script src="build/react.js"></script>
<!-- No need for JSXTransformer! -->
</head>
<body>
@@ -115,4 +115,4 @@ If you want to use React within a module system, [fork our repo](http://github.c
## Next Steps
Check out [the tutorial](tutorial.html) and the other examples in the `/examples` directory to learn more. Good luck, and welcome!
Check out [the tutorial](/react/docs/tutorial.html) and the other examples in the `/examples` directory to learn more. Good luck, and welcome!

View File

@@ -31,9 +31,9 @@ Configure React's event system to handle touch events on mobile devices.
function createClass(object specification)
```
Creates a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
Create a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
For more information about the specification object, see [Component Specs and Lifecycle](component-specs.html).
For more information about the specification object, see [Component Specs and Lifecycle](/react/docs/component-specs.html).
### React.renderComponent
@@ -46,20 +46,24 @@ ReactComponent renderComponent(
)
```
Renders a React component into the DOM in the supplied `container`.
Render a React component 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 optional callback is provided, it will be executed after the component is rendered or updated.
### React.unmountAndReleaseReactRootNode
### React.unmountComponentAtNode
```javascript
unmountAndReleaseReactRootNode(DOMElement container)
boolean unmountComponentAtNode(DOMElement container)
```
Remove a mounted React component from the DOM and clean up its event handlers and state.
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.
> Note:
>
> This method was called `React.unmountAndReleaseReactRootNode` until v0.5. It still works in v0.5 but will be removed in future versions.
### React.renderComponentToString

View File

@@ -9,7 +9,7 @@ next: component-specs.html
## ReactComponent
Component classses created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
Component classes created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
### getDOMNode
@@ -60,7 +60,7 @@ var Avatar = React.createClass({
}
});
// <AvatarImage userId={17} width={200} height={200} />
// <Avatar userId={17} width={200} height={200} />
```
Properties that are specified directly on the target component instance (such as `src` and `userId` in the above example) will not be overwritten by `transferPropsTo`.
@@ -107,3 +107,12 @@ If your `render()` method reads from something other than `this.props` or `this.
Calling `forceUpdate()` will cause `render()` to be called on the component and its children, but React will still only update the DOM if the markup changes.
Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your application much simpler and more efficient.
### isMounted()
```javascript
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()`.

View File

@@ -20,7 +20,7 @@ ReactComponent render()
The `render()` method is required.
When called, it should examine `this.props` and `this.state` and return a single child component. This child component can be either a native DOM component (such as `<div>`) or another composite component that you've defined yourself.
When called, it should examine `this.props` and `this.state` and return a single child component. This child component can be either a virtual representation of a native DOM component (such as `<div />` or `React.DOM.div()`) or another composite component that you've defined yourself.
The `render()` function should be *pure*, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using `setTimeout`). If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes server rendering more practical and makes components easier to think about.
@@ -31,7 +31,7 @@ The `render()` function should be *pure*, meaning that it does not modify compon
object getInitialState()
```
Invoked once when the component is mounted. The return value will be used as the initial value of `this.state`.
Invoked once before the component is mounted. The return value will be used as the initial value of `this.state`.
### getDefaultProps
@@ -51,7 +51,7 @@ This method is invoked before `getInitialState` and therefore cannot rely on `th
object propTypes
```
The `propTypes` object allows you to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](reusable-components.html).
The `propTypes` object allows you to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html).
<!-- TODO: Document propTypes here directly. -->
@@ -62,11 +62,20 @@ The `propTypes` object allows you to validate props being passed to your compone
array mixins
```
The `mixins` array allows you to use mixins to share behavior among multiple components. For more information about mixins, see [Reusable Components](reusable-components.html).
The `mixins` array allows you to use mixins to share behavior among multiple components. For more information about mixins, see [Reusable Components](/react/docs/reusable-components.html).
<!-- TODO: Document mixins here directly. -->
### displayName
```javascript
string displayName
```
The `displayName` string is used in debugging messages. JSX sets this value automatically, see [JSX in Depth](/react/docs/jsx-in-depth.html#react-composite-components).
## Lifecycle Methods
Various methods are executed at specific points in a component's lifecycle.
@@ -78,7 +87,7 @@ Various methods are executed at specific points in a component's lifecycle.
componentWillMount()
```
Invoked immediately before rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change.
Invoked once, immediately before the initial rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change.
### Mounting: componentDidMount

View File

@@ -11,11 +11,10 @@ next: events.html
React attempts to support all common elements. If you need an element that isn't listed here, please file an issue.
The following elements are supported:
### HTML Elements
The following HTML elements are supported:
```
a abbr address area article aside audio b base bdi bdo big blockquote body br
button canvas caption cite code col colgroup data datalist dd del details dfn
@@ -29,17 +28,24 @@ title tr track u ul var video wbr
### SVG elements
The following SVG elements are supported:
```
circle g line path polyline rect svg text
circle g line path polygon polyline rect svg text
```
You may also be interested in [react-art](https://github.com/facebook/react-art), a drawing library for React that can render to Canvas, SVG, or VML (for IE8).
## Supported Attributes
React supports all `data-*` and `aria-*` attributes as well as every attribute
in the following lists. Note that all attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
React supports all `data-*` and `aria-*` attributes as well as every attribute in the following lists.
For a list of events, see [Supported Events](events.html).
> Note:
>
> All attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
For a list of events, see [Supported Events](/react/docs/events.html).
### HTML Attributes
@@ -48,13 +54,15 @@ accept accessKey action allowFullScreen allowTransparency alt autoCapitalize
autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked
className colSpan content contentEditable contextMenu controls data dateTime
dir disabled draggable encType form frameBorder height hidden href htmlFor
httpEquiv icon id label lang list max maxLength method min multiple name
httpEquiv icon id label lang list loop max maxLength method min multiple name
pattern placeholder poster preload radioGroup readOnly rel required role
rowSpan scrollLeft scrollTop selected size spellCheck src step style tabIndex
target title type value width wmode
```
In addition, the non-standard `autoCapitalize` attribute is supported for Mobile Safari.
The non-standard `autoCapitalize` attribute is supported for Mobile Safari.
In addition, there is the React-specific attribute `dangerouslySetInnerHTML` ([more here](/react/docs/special-non-dom-attributes.html)), used for directly inserting DOM strings into a component.
### SVG Attributes

View File

@@ -62,14 +62,16 @@ Properties:
```javascript
boolean altKey
String char
boolean ctrlKey
Number charCode
String key
Number keyCode
String locale
Number location
boolean metaKey
boolean repeat
boolean shiftKey
Number which
```
@@ -96,7 +98,7 @@ Event names:
onChange onInput onSubmit
```
For more information about the onChange event, see [Forms](forms.html).
For more information about the onChange event, see [Forms](/react/docs/forms.html).
### Mouse Events
@@ -128,25 +130,6 @@ boolean shiftKey
```
### Mutation Events
Event names:
```
onDOMCharacterDataModified
```
Properties:
```javascript
Number attrChange
String attrName
String newValue
String prevValue
Node relatedNode
```
### Touch events
To enable touch events, call `React.initializeTouchEvents(true)` before

View File

@@ -4,11 +4,13 @@ title: DOM Differences
layout: docs
permalink: dom-differences.html
prev: events.html
next: special-non-dom-attributes.html
---
React has implemented a browser-independent events and DOM system for performance and cross-browser compatibility reasons. We took the opportunity to clean up a few rough edges in browser DOM implementations.
* All DOM properties and attributes (including event handlers) should be camelCased to be consistent with standard JavaScript style. We intentionally break with the spec here since the spec is inconsistent.
* The `style` attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM `style` JavaScript property, is more efficient, and prevents XSS security holes.
* All event objects conform to the W3C spec, and all events (including submit) bubble correctly per the W3C spec. See [Event System](events.html) for more details.
* The `onChange` event behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time. See [Forms](forms.html) for more details.
* All event objects conform to the W3C spec, and all events (including submit) bubble correctly per the W3C spec. See [Event System](/react/docs/events.html) for more details.
* The `onChange` event behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time. See [Forms](/react/docs/forms.html) for more details.
* Form input attributes such as `value` and `checked`, as well as `textarea`. [More here](/react/docs/forms.html).

View File

@@ -0,0 +1,14 @@
---
id: special-non-dom-attributes
title: Special Non-DOM Attributes
layout: docs
permalink: special-non-dom-attributes.html
prev: dom-differences.html
next: reconciliation.html
---
Beside [DOM differences](/react/docs/dom-differences.html), React offers some attributes that simply don't exist in DOM.
- `key`: an optional, unique identifier. When your component shuffles around during `render` passes, it might be destroyed and recreated due to the diff algorithm. Assigning it a key that persists makes sure the component stays. See more [here](/react/docs/multiple-components.html#dynamic-children).
- `ref`: see [here](/react/docs/more-about-refs.html).
- `dangerouslySetInnerHTML`: takes an object with the key `__html` and a DOM string as value. This is mainly for cooperating with DOM string manipulation libraries. Refer to the last example on the front page.

View File

@@ -0,0 +1,133 @@
---
id: reconciliation
title: Reconciliation
layout: docs
permalink: reconciliation.html
prev: special-non-dom-attributes.html
---
React 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.
## Motivation
Generating the minimum number of operations to transform one tree into another is a complex and well-studied problem. The [state of the art algorithms](http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) have a complexity in the order of O(n<sup>3</sup>) where n is the number of nodes in the tree.
This means that displaying 1000 nodes would require in the order of one billion comparisons. This is far too expensive for our use case. To put this number in perspective, CPUs nowadays execute roughly 3 billion instruction per second. So even with the most performant implementation, we wouldn't be able to compute that diff in less than a second.
Since an optimal algorithm is not tractable, we implement a non-optimal O(n) algorithm using heuristics based on two assumptions:
1. Two components of the same class will generate similar trees and two components of different classes will generate different trees.
2. It is possible to provide a unique key for elements that is stable across different renders.
In practice, these assumptions are ridiculously fast for almost all practical use cases.
## Pair-wise diff
In order to do a tree diff, we first need to be able to diff two nodes. There are three different cases being handled.
### Different Node Types
If the node type is different, React is going to treat them as two different sub-trees, throw away the first one and build/insert the second one.
```xml
renderA: <div />
renderB: <span />
=> [removeNode <div />], [insertNode <span />]
```
The same logic is used for custom components. If they are not of the same type, React is not going to even try at matching what they render. It is just going to remove the first one from the DOM and insert the second one.
```xml
renderA: <Header />
renderB: <Content />
=> [removeNode <Header />], [insertNode <Content />]
```
Having this high level knowledge is a very important aspect of why React diff algorithm is both fast and precise. It provides a good heuristic to quickly prune big parts of the tree and focus on parts likely to be similar.
It is very unlikely that a `<Header>` element is going generate a DOM that is going to look like what a `<Content>` would generate. Instead of spending time trying to match those two structures, React just re-builds the tree from scratch.
As a corollary, if there is a `<Header>` element at the same position in two consecutive renders, you would expect to see a very similar structure and it is worth exploring it.
### DOM Nodes
When comparing two DOM nodes, we look at the attributes of both and can decide which of them changed in linear time.
```xml
renderA: <div id="before" />
renderB: <div id="after" />
=> [replaceAttribute id "after"]
```
Instead of treating style as an opaque string, a key-value object is used instead. This lets us update only the properties that changed.
```xml
renderA: <div style={{'{{'}}color: 'red'}} />
renderB: <div style={{'{{'}}fontWeight: 'bold'}} />
=> [removeStyle color], [addStyle font-weight 'bold']
```
After the attributes have been updated, we recurse on all the children.
### Custom Components
We decided that the two custom components are the same. Since components are stateful, we cannot just use the new component and call it a day. React takes all the attributes from the new component and call `component[Will/Did]ReceiveProps()` on the previous one.
The previous component is now operational. Its `render()` method is called and the diff algorithm restarts with the new result and the previous result.
## List-wise diff
### Problematic Case
In order to do children reconciliation, React adopts a very naive approach. It goes over the list of children both at the same time and whenever there's a difference generates a mutation.
For example if you add an element at the end:
```xml
renderA: <div><span>first</span></div>
renderB: <div><span>first</span><span>second</span></div>
=> [insertNode <span>second</span>]
```
Inserting an element at the beginning is problematic. React is going to see that both nodes are spans and therefore run into a mutation mode.
```xml
renderA: <div><span>first</span></div>
renderB: <div><span>second</span><span>first</span></div>
=> [replaceAttribute textContent 'second'], [insertNode <span>first</span>]
```
There are many algorithms that attempt to find the minimum sets of operations to transform a list of elements. [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) can find the minimum using single element insertion, deletion and substitution in O(n<sup>2</sup>). Even if we were to use Levenshtein, this doesn't find when a node has moved into another position and algorithms to do that have much worse complexity.
### Keys
In order to solve this seemingly intractable issue, an optional attribute has been introduced. You can provide for each child a key that is going to be used to do the matching. If you specify a key, React is now able to find insertion, deletion, substitution and moves in O(n) using a hash table.
```xml
renderA: <div><span key="first">first</span></div>
renderB: <div><span key="second">second</span><span key="first">first</span></div>
=> [insertNode <span>second</span>]
```
In practice, finding a key is not really hard. Most of the time, the element you are going to display already have a unique id. When it is not the case, you can hash some parts of the content to generate an id. Remember that the id only has to be unique among its sibling, not globally unique.
## Trade-offs
It is important to remember that the reconciliation algorithm is an implementation detail. React could re-render the whole app on every action, the end-result would be the same. We are regularly refining the heuristics in order to make common use cases faster.
In the current implementation, you can express the fact that a sub-tree has been moved between siblings, but you cannot tell that it has moved somewhere else. The algorithm will re-render that full sub-tree.
Because we rely on two heuristics, if the assumptions behind them are not met, performance will suffer.
1. The algorithm will not try to match sub-trees of different components classes. If you see yourself alternating between two components classes with very similar output, you may want to make it the same class. In practice, we haven't found this to be an issue.
2. If you don't provide stable keys (by using Math.random() for example), all the sub-trees are going to be re-rendered every single time. By giving the users the choice to chose the key, they have the ability to shoot themselves in the foot.

View File

@@ -2,7 +2,10 @@
id: tutorial
title: Tutorial
layout: docs
prev: getting-started.html
next: videos.html
---
We'll be building a simple, but realistic comments box that you can drop into a blog, similar to Disqus, LiveFyre or Facebook comments.
We'll provide:
@@ -32,6 +35,7 @@ For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your fav
<title>Hello React</title>
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
</head>
<body>
<div id="content"></div>
@@ -39,6 +43,7 @@ For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your fav
/**
* @jsx React.DOM
*/
// The above declaration must remain intact at the top of the script.
// Your code here
</script>
</body>
@@ -65,7 +70,7 @@ Let's build the `CommentBox` component, which is just a simple `<div>`:
var CommentBox = React.createClass({
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
Hello, world! I am a CommentBox.
</div>
);
@@ -99,7 +104,7 @@ React.renderComponent(
);
```
Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](jsx-in-depth.html).
Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](/react/docs/jsx-in-depth.html).
#### What's going on
@@ -120,7 +125,7 @@ Let's build skeletons for `CommentList` and `CommentForm` which will, again, be
var CommentList = React.createClass({
render: function() {
return (
<div class="commentList">
<div className="commentList">
Hello, world! I am a CommentList.
</div>
);
@@ -130,7 +135,7 @@ var CommentList = React.createClass({
var CommentForm = React.createClass({
render: function() {
return (
<div class="commentForm">
<div className="commentForm">
Hello, world! I am a CommentForm.
</div>
);
@@ -145,7 +150,7 @@ Next, update the `CommentBox` component to use its new friends:
var CommentBox = React.createClass({
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList />
<CommentForm />
@@ -166,7 +171,7 @@ Let's create our third component, `Comment`. We will want to pass it the author
var CommentList = React.createClass({
render: function() {
return (
<div class="commentList">
<div className="commentList">
<Comment author="Pete Hunt">This is one comment</Comment>
<Comment author="Jordan Walke">This is *another* comment</Comment>
</div>
@@ -186,8 +191,8 @@ Let's create the Comment component. It will read the data passed to it from the
var Comment = React.createClass({
render: function() {
return (
<div class="comment">
<h2 class="commentAuthor">
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
@@ -223,8 +228,8 @@ var converter = new Showdown.converter();
var Comment = React.createClass({
render: function() {
return (
<div class="comment">
<h2 class="commentAuthor">
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{converter.makeHtml(this.props.children.toString())}
@@ -247,8 +252,8 @@ var Comment = React.createClass({
render: function() {
var rawMarkup = converter.makeHtml(this.props.children.toString());
return (
<div class="comment">
<h2 class="commentAuthor">
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={{"{{"}}__html: rawMarkup}} />
@@ -281,7 +286,7 @@ We need to get this data into `CommentList` in a modular way. Modify `CommentBox
var CommentBox = React.createClass({
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.props.data} />
<CommentForm />
@@ -306,7 +311,7 @@ var CommentList = React.createClass({
return <Comment author={comment.author}>{comment.text}</Comment>;
});
return (
<div class="commentList">
<div className="commentList">
{commentNodes}
</div>
);
@@ -320,7 +325,7 @@ That's it!
Let's replace the hard-coded data with some dynamic data from the server. We will remove the data prop and replace it with a URL to fetch:
```javascript{2}
```javascript{3}
// tutorial11.js
React.renderComponent(
<CommentBox url="comments.json" />,
@@ -346,7 +351,7 @@ var CommentBox = React.createClass({
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
@@ -369,27 +374,31 @@ When the component is first created, we want to GET some JSON from the server an
]
```
We will use jQuery 1.5 to help make an asynchronous request to the server.
We'll use jQuery to help make an asynchronous request to the server.
Note: because this is becoming an AJAX application you'll need to develop your app using a web server rather than as a file sitting on your file system. The easiest way to do this is to run `python -m SimpleHTTPServer` in your application's directory.
```javascript{4-11}
```javascript{6-17}
// tutorial13.js
var CommentBox = React.createClass({
getInitialState: function() {
return {data: []};
},
componentWillMount: function() {
$.ajax({
url: 'comments.json',
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error("comments.json", status, err.toString());
}.bind(this)
});
return {data: []};
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
@@ -399,16 +408,15 @@ var CommentBox = React.createClass({
});
```
The key is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is trivial to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
Here, `componentWillMount` is a method called automatically by React before a component is rendered. The key to dynamic updates is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is trivial to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
```javascript{3,17-21,35}
```javascript{3,16-17,31}
// tutorial14.js
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -419,14 +427,11 @@ var CommentBox = React.createClass({
},
componentWillMount: function() {
this.loadCommentsFromServer();
setInterval(
this.loadCommentsFromServer.bind(this),
this.props.pollInterval
);
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
@@ -436,13 +441,13 @@ var CommentBox = React.createClass({
});
React.renderComponent(
<CommentBox url="comments.json" pollInterval={5000} />,
<CommentBox url="comments.json" pollInterval={2000} />,
document.getElementById('content')
);
```
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 5 seconds after that. Try running this in your browser and changing the `comments.json` file; within 5 seconds, the changes will show!
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 2 seconds after that. Try running this in your browser and changing the `comments.json` file; within 2 seconds, the changes will show!
### Adding new comments
@@ -453,10 +458,10 @@ Now it's time to build the form. Our `CommentForm` component should ask the user
var CommentForm = React.createClass({
render: function() {
return (
<form class="commentForm">
<form className="commentForm">
<input type="text" placeholder="Your name" />
<input type="text" placeholder="Say something..." />
<input type="submit" />
<input type="submit" value="Post" />
</form>
);
}
@@ -465,7 +470,7 @@ var CommentForm = React.createClass({
Let's make the form interactive. When the user submits the form, we should clear it, submit a request to the server, and refresh the list of comments. To start, let's listen for the form's submit event and clear it.
```javascript{3-13,16,21}
```javascript{3-13,16-17,21}
// tutorial16.js
var CommentForm = React.createClass({
handleSubmit: function() {
@@ -481,14 +486,14 @@ var CommentForm = React.createClass({
},
render: function() {
return (
<form class="commentForm" onSubmit={this.handleSubmit}>
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" />
<input
type="text"
placeholder="Say something..."
ref="text"
/>
<input type="submit" />
<input type="submit" value="Post" />
</form>
);
}
@@ -511,14 +516,13 @@ When a user submits a comment, we will need to refresh the list of comments to i
We need to pass data from the child component to its parent. We do this by passing a `callback` in props from parent to child:
```javascript{13-15,32}
```javascript{12-14,28}
// tutorial17.js
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -532,14 +536,11 @@ var CommentBox = React.createClass({
},
componentWillMount: function() {
this.loadCommentsFromServer();
setInterval(
this.loadCommentsFromServer.bind(this),
this.props.pollInterval
);
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm
@@ -566,14 +567,14 @@ var CommentForm = React.createClass({
},
render: function() {
return (
<form class="commentForm" onSubmit={this.handleSubmit}>
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" />
<input
type="text"
placeholder="Say something..."
ref="text"
/>
<input type="submit" />
<input type="submit" value="Post" />
</form>
);
}
@@ -582,14 +583,13 @@ var CommentForm = React.createClass({
Now that the callbacks are in place, all we have to do is submit to the server and refresh the list:
```javascript{14-22}
```javascript{13-21}
// tutorial19.js
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -598,9 +598,9 @@ var CommentBox = React.createClass({
handleCommentSubmit: function(comment) {
$.ajax({
url: this.props.url,
data: comment,
dataType: 'json',
mimeType: 'textPlain',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -611,14 +611,11 @@ var CommentBox = React.createClass({
},
componentWillMount: function() {
this.loadCommentsFromServer();
setInterval(
this.loadCommentsFromServer.bind(this),
this.props.pollInterval
);
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm
@@ -634,14 +631,13 @@ var CommentBox = React.createClass({
Our application is now feature complete but it feels slow to have to wait for the request to complete before your comment appears in the list. We can optimistically add this comment to the list to make the app feel faster.
```javascript{14-16}
```javascript{13-15}
// tutorial20.js
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -649,13 +645,13 @@ var CommentBox = React.createClass({
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
comments.push(comment);
this.setState({data: comments});
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
data: comment,
dataType: 'json',
mimeType: 'textPlain',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -666,14 +662,11 @@ var CommentBox = React.createClass({
},
componentWillMount: function() {
this.loadCommentsFromServer();
setInterval(
this.loadCommentsFromServer.bind(this),
this.props.pollInterval
);
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm
@@ -687,4 +680,4 @@ var CommentBox = React.createClass({
### Congrats!
You have just built a comment box in a few simple steps. Learn more about [why to use React](why-react.html), or dive into the [API reference](top-level-api.html) and start hacking! Good luck!
You have just built a comment box in a few simple steps. Learn more about [why to use React](/react/docs/why-react.html), or dive into the [API reference](/react/docs/top-level-api.html) and start hacking! Good luck!

68
docs/docs/videos.md Normal file
View File

@@ -0,0 +1,68 @@
---
id: videos
title: Videos
layout: docs
permalink: videos.html
prev: tutorial.html
next: complementary-tools.html
---
### Rethinking best practices - JSConf.eu
<iframe width="650" height="315" src="//www.youtube.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
"At Facebook and Instagram, were trying to push the limits of whats possible on the web with React. My talk will start with a brief introduction to the framework, and then dive into three controversial topics: Throwing out the notion of templates and building views with JavaScript, “re-rendering” your entire application when your data changes, and a lightweight implementation of the DOM and events." -- [Pete Hunt](http://www.petehunt.net/)
### JavaScript Jabber
[Pete Hunt](http://www.petehunt.net/) and [Jordan Walke](https://github.com/jordwalke) talked about React in JavaScript Jabber 73.
<figure>[![](/react/img/docs/javascript-jabber.png)](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/#content)</figure>
<table width="100%"><tr><td>
01:34 Pete Hunt Introduction<br />
02:45 Jordan Walke Introduction<br />
04:15 React<br />
06:38 60 Frames Per Second<br />
09:34 Data Binding<br />
12:31 Performance<br />
17:39 Diffing Algorithm<br />
19:36 DOM Manipulation
</td><td>
23:06 Supporting node.js<br />
24:03 rendr<br />
26:02 JSX<br />
30:31 requestAnimationFrame<br />
34:15 React and Applications<br />
38:12 React Users Khan Academy<br />
39:53 Making it work
</td></tr></table>
[Read the full transcript](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/)
### Introduction to React.js - Facebook Seattle
<iframe width="650" height="315" src="//www.youtube.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
By [Tom Occhino](http://tomocchino.com/) and [Jordan Walke](https://github.com/jordwalke)
### Developing User Interfaces With React - Super VanJS
<iframe width="650" height="315" src="//www.youtube.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
By [Steven Luscher](https://github.com/steveluscher)
### Introduction to React - Joe Dev on Tech
<iframe width="650" height="315" src="//www.youtube.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
by [Stoyan Stefanov](http://www.phpied.com/)
### "fun + React + ClojureScript" - Small Talk KyivJS Meetup
<iframe width="650" height="315" src="//www.youtube.com/embed/R2CGKiNnPFo" frameborder="0" allowfullscreen></iframe>
**In Russian** by [Alexander Solovyov](http://solovyov.net/)
### "Functional DOM programming" - Meteor DevShop 11
<iframe width="650" height="315" src="//www.youtube.com/embed/Lqcs6hPOcFw?t=49m23s" frameborder="0" allowfullscreen></iframe>

View File

@@ -4,7 +4,7 @@ title: Downloads
layout: single
---
Download the starter kit to get everything you need to
[get started with React](/react/docs/getting-started.html).
[get started with React](/react/docs/getting-started.html). The starter kit includes React, the in-browser JSX transformer, and some simple example apps.
<div class="buttons-unit downloads">
<a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
@@ -12,30 +12,50 @@ Download the starter kit to get everything you need to
</a>
</div>
## Development vs. Production Builds
We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
If you're just starting out, make sure to use the development version.
## Individual Downloads
#### <a href="http://fb.me/react-{{site.react_version}}.min.js">React Core {{site.react_version}} (production)</a>
The compressed, production version of React core
```html
<script src="http://fb.me/react-{{site.react_version}}.min.js"></script>
```
#### <a href="http://fb.me/react-{{site.react_version}}.js">React Core {{site.react_version}} (development)</a>
#### <a href="http://fb.me/react-{{site.react_version}}.js">React {{site.react_version}} (development)</a>
The uncompressed, development version of React core with inline documentation.
```html
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
```
#### <a href="http://fb.me/JSXTransformer-{{site.react_version}}.js">JSX Transform</a>
#### <a href="http://fb.me/react-{{site.react_version}}.min.js">React {{site.react_version}} (production)</a>
The compressed, production version of React core.
```html
<script src="http://fb.me/react-{{site.react_version}}.min.js"></script>
```
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.js">React with Add-Ons {{site.react_version}} (development)</a>
The uncompressed, development version of React with [add-ons](/react/docs/addons.html).
```html
<script src="http://fb.me/react-with-addons-{{site.react_version}}.js"></script>
```
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.min.js">React with Add-Ons {{site.react_version}} (production)</a>
The compressed, production version of React with [add-ons](/react/docs/addons.html).
```html
<script src="http://fb.me/react-with-addons-{{site.react_version}}.min.js"></script>
```
#### <a href="http://fb.me/JSXTransformer-{{site.react_version}}.js">JSX Transformer</a>
The JSX transformer used to support [XML syntax](/react/docs/jsx-in-depth.html) in JavaScript.
```html
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
```
All scripts are also available via [CDNJS](http://cdnjs.com/#react).
All scripts are also available via [CDNJS](http://cdnjs.com/libraries/react/).
## Bower

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

11
docs/html-jsx.md Normal file
View File

@@ -0,0 +1,11 @@
---
layout: default
title: HTML to JSX
id: html-jsx
---
<div class="jsxCompiler">
<h1>HTML to JSX Compiler</h1>
<div id="jsxCompiler"></div>
<script src="js/html-jsx-lib.js"></script>
<script src="js/html-jsx.js"></script>
</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
docs/img/blog/ngreact.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

BIN
docs/img/blog/react-php.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
docs/img/blog/tutsplus.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

BIN
docs/img/blog/xoxo2013.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Some files were not shown because too many files have changed in this diff Show More