Compare commits

...

129 Commits

Author SHA1 Message Date
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
134 changed files with 4239 additions and 791 deletions

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

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.5.2.js"></script>
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<script src="http://fb.me/JSXTransformer-0.4.1.js"></script>
<script src="http://fb.me/JSXTransformer-0.5.2.js"></script>
```
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.4.1.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.5.2.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
If you'd like to use [bower](http://bower.io), it's as easy as:
@@ -51,7 +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,8 @@ 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/

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 {
@@ -369,6 +387,8 @@ section.black content {
*/
.blogContent {
@include clearfix;
padding-top: 20px;
blockquote {
@@ -391,6 +411,7 @@ section.black content {
font-size: 24px;
}
// H2s form documentation topic dividers. Extra space helps.
h2 {
margin-top: 30px;
@@ -438,7 +459,7 @@ section.black content {
}
.playgroundPreview {
padding: 14px;
padding: 0;
width: 600px;
pre {

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

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

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

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

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>

View File

@@ -18,7 +18,7 @@ var Timer = React.createClass({\n\
},\n\
render: function() {\n\
return React.DOM.div({},\n\
'Seconds Elapsed: ' + this.state.secondsElapsed\n\
'Seconds Elapsed: ', this.state.secondsElapsed\n\
);\n\
}\n\
});\n\

View File

@@ -22,7 +22,8 @@ var CodeMirrorEditor = React.createClass({
mode: 'javascript',
lineNumbers: false,
matchBrackets: true,
theme: 'solarized-light'
theme: 'solarized-light',
readOnly: this.props.readOnly
});
this.editor.on('change', this.onChange);
this.onChange();
@@ -44,7 +45,7 @@ var CodeMirrorEditor = React.createClass({
}
return (
<div class={this.props.className}>
<div className={this.props.className}>
{editor}
</div>
);
@@ -76,22 +77,22 @@ var ReactPlayground = React.createClass({
content =
<CodeMirrorEditor
onChange={this.bindState('code')}
class="playgroundStage"
className="playgroundStage"
codeText={this.state.code}
/>;
} else if (this.state.mode === this.MODES.JS) {
content =
<div class="playgroundJS playgroundStage">
{this.getDesugaredCode()}
<div className="playgroundJS playgroundStage">
{this.getDesugaredCode()}
</div>;
}
return (
<div class="playground">
<div class="playgroundCode">
<div className="playground">
<div className="playgroundCode">
{content}
</div>
<div class="playgroundPreview">
<div className="playgroundPreview">
<div ref="mount" />
</div>
</div>
@@ -111,17 +112,18 @@ var ReactPlayground = React.createClass({
} catch (e) { }
try {
var desugaredCode = this.getDesugaredCode();
if (this.props.renderCode) {
React.renderComponent(
<pre>{this.getDesugaredCode()}</pre>,
<CodeMirrorEditor codeText={desugaredCode} readOnly={true} />,
mountNode
);
} else {
eval(this.getDesugaredCode());
eval(desugaredCode);
}
} catch (e) {
React.renderComponent(
<div content={e.toString()} class="playgroundError" />,
<div content={e.toString()} className="playgroundError" />,
mountNode
);
}

View File

@@ -74,6 +74,7 @@
</footer>
</div>
<div id="fb-root"></div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

25
docs/_layouts/tips.html Normal file
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

@@ -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 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

@@ -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

@@ -157,19 +157,6 @@ It's easy to add comments within your JSX; they're just JS expressions:
var content = <Container>{/* this is a comment */}<Nav /></Container>;
```
## Tooling
Beyond the compilation step, JSX does not require any special tools.
* Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
* JSX syntax highlighting is available for Sublime Text and other editors
that support `*.tmLanguage` using the third-party
[`JavaScript (JSX).tmLanguage`][1].
* Linting provides accurate line numbers after compiling without sourcemaps.
* Elements use standard scoping so linters can find usage of out-of-scope
components.
[1]: https://github.com/yungsters/sublime/blob/master/tmLanguage/JavaScript%20(JSX).tmLanguage
## Prior Work

View File

@@ -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

@@ -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

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

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={i} onClick={this.handleRemove.bind(this, i)}>
{item}
</div>
);
}.bind(this));
return (
<div>
<div><button onClick={this.handleAdd} /></div>
<ReactTransitionGroup transitionName="example">
{items}
</ReactTransitionGroup>
</div>
);
}
});
```
In this component, when a new item is added to `ReactTransitionGroup` it will get the `example-enter` CSS class and the `example-enter-active` CSS class added in the next tick. This is a convention based on the `transitionName` prop.
You can use these classes to trigger a CSS animation or transition. For example, try adding this CSS and adding a new list item:
```css
.example-enter {
opacity: 0.01;
transition: opacity .5s ease-in;
}
.example-enter.example-enter-active {
opacity: 1;
}
```
You'll notice that when you try to remove an item `ReactTransitionGroup` keeps it in the DOM. If you're using an unminified build of React with add-ons you'll see a warning that React was expecting an animation or transition to occur. That's because `ReactTransitionGroup` keeps your DOM elements on the page until the animation completes. Try adding this CSS:
```css
.example-leave {
opacity: 1;
transition: opacity .5s ease-in;
}
.example-leave.example-leave-active {
opacity: 0.01;
}
```
## Disabling Animations
You can disable animating `enter` or `leave` animations if you want. For example, sometimes you may want an `enter` animation and no `leave` animation, but `ReactTransitionGroup` waits for an animation to complete before removing your DOM node. You can add `transitionEnter={false}` or `transitionLeave={false}` props to `ReactTransitionGroup` to disable these animations.
## Rendering a Different Component
By default `ReactTransitionGroup` renders as a `span`. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`:
```javascript{3}
<ReactTransitionGroup
transitionName="example"
component={React.DOM.ul}>
...
</ReactTransitionGroup>
```
Every DOM component is under `React.DOM`. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself!

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](./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!

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

@@ -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

@@ -53,14 +53,18 @@ If the React component was previously rendered into `container`, this will perfo
If the optional callback is provided, it will be executed after the component is rendered or updated.
### React.unmountAndReleaseReactRootNode
### React.unmountComponentAtNode
```javascript
unmountAndReleaseReactRootNode(DOMElement container)
unmountComponentAtNode(DOMElement container)
```
Remove a mounted React component from the DOM and clean up its event handlers and state.
> Note:
>
> This method was called `React.unmountAndReleaseReactRootNode` until v0.5. It still works in v0.5 but will be removed in future versions.
### React.renderComponentToString

View File

@@ -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`.

View File

@@ -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

View File

@@ -36,8 +36,11 @@ circle g line path polyline rect svg text
## Supported Attributes
React supports all `data-*` and `aria-*` attributes as well as every attribute
in the following lists. Note that all attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
React supports all `data-*` and `aria-*` attributes as well as every attribute in the following lists.
> Note:
>
> All attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
For a list of events, see [Supported Events](events.html).
@@ -48,7 +51,7 @@ 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

View File

@@ -128,25 +128,6 @@ boolean shiftKey
```
### Mutation Events
Event names:
```
onDOMCharacterDataModified
```
Properties:
```javascript
Number attrChange
String attrName
String newValue
String prevValue
Node relatedNode
```
### Touch events
To enable touch events, call `React.initializeTouchEvents(true)` before

View File

@@ -65,7 +65,7 @@ Let's build the `CommentBox` component, which is just a simple `<div>`:
var CommentBox = React.createClass({
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
Hello, world! I am a CommentBox.
</div>
);
@@ -120,7 +120,7 @@ Let's build skeletons for `CommentList` and `CommentForm` which will, again, be
var CommentList = React.createClass({
render: function() {
return (
<div class="commentList">
<div className="commentList">
Hello, world! I am a CommentList.
</div>
);
@@ -130,7 +130,7 @@ var CommentList = React.createClass({
var CommentForm = React.createClass({
render: function() {
return (
<div class="commentForm">
<div className="commentForm">
Hello, world! I am a CommentForm.
</div>
);
@@ -145,7 +145,7 @@ Next, update the `CommentBox` component to use its new friends:
var CommentBox = React.createClass({
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList />
<CommentForm />
@@ -166,7 +166,7 @@ Let's create our third component, `Comment`. We will want to pass it the author
var CommentList = React.createClass({
render: function() {
return (
<div class="commentList">
<div className="commentList">
<Comment author="Pete Hunt">This is one comment</Comment>
<Comment author="Jordan Walke">This is *another* comment</Comment>
</div>
@@ -186,8 +186,8 @@ Let's create the Comment component. It will read the data passed to it from the
var Comment = React.createClass({
render: function() {
return (
<div class="comment">
<h2 class="commentAuthor">
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
@@ -223,8 +223,8 @@ var converter = new Showdown.converter();
var Comment = React.createClass({
render: function() {
return (
<div class="comment">
<h2 class="commentAuthor">
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{converter.makeHtml(this.props.children.toString())}
@@ -247,8 +247,8 @@ var Comment = React.createClass({
render: function() {
var rawMarkup = converter.makeHtml(this.props.children.toString());
return (
<div class="comment">
<h2 class="commentAuthor">
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={{"{{"}}__html: rawMarkup}} />
@@ -281,7 +281,7 @@ We need to get this data into `CommentList` in a modular way. Modify `CommentBox
var CommentBox = React.createClass({
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.props.data} />
<CommentForm />
@@ -306,7 +306,7 @@ var CommentList = React.createClass({
return <Comment author={comment.author}>{comment.text}</Comment>;
});
return (
<div class="commentList">
<div className="commentList">
{commentNodes}
</div>
);
@@ -346,7 +346,7 @@ var CommentBox = React.createClass({
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
@@ -369,7 +369,7 @@ When the component is first created, we want to GET some JSON from the server an
]
```
We will use jQuery 1.5 to help make an asynchronous request to the server.
We will use jQuery to help make an asynchronous request to the server.
Note: because this is becoming an AJAX application you'll need to develop your app using a web server rather than as a file sitting on your file system. The easiest way to do this is to run `python -m SimpleHTTPServer` in your application's directory.
@@ -379,8 +379,6 @@ var CommentBox = React.createClass({
getInitialState: function() {
$.ajax({
url: 'comments.json',
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -389,7 +387,7 @@ var CommentBox = React.createClass({
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
@@ -407,8 +405,6 @@ var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -419,14 +415,11 @@ var CommentBox = React.createClass({
},
componentWillMount: function() {
this.loadCommentsFromServer();
setInterval(
this.loadCommentsFromServer.bind(this),
this.props.pollInterval
);
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
@@ -436,13 +429,13 @@ var CommentBox = React.createClass({
});
React.renderComponent(
<CommentBox url="comments.json" pollInterval={5000} />,
<CommentBox url="comments.json" pollInterval={2000} />,
document.getElementById('content')
);
```
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 5 seconds after that. Try running this in your browser and changing the `comments.json` file; within 5 seconds, the changes will show!
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 2 seconds after that. Try running this in your browser and changing the `comments.json` file; within 2 seconds, the changes will show!
### Adding new comments
@@ -453,10 +446,10 @@ Now it's time to build the form. Our `CommentForm` component should ask the user
var CommentForm = React.createClass({
render: function() {
return (
<form class="commentForm">
<form className="commentForm">
<input type="text" placeholder="Your name" />
<input type="text" placeholder="Say something..." />
<input type="submit" />
<input type="submit" value="Post" />
</form>
);
}
@@ -481,14 +474,14 @@ var CommentForm = React.createClass({
},
render: function() {
return (
<form class="commentForm" onSubmit={this.handleSubmit}>
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" />
<input
type="text"
placeholder="Say something..."
ref="text"
/>
<input type="submit" />
<input type="submit" value="Post" />
</form>
);
}
@@ -517,8 +510,6 @@ var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -532,14 +523,11 @@ var CommentBox = React.createClass({
},
componentWillMount: function() {
this.loadCommentsFromServer();
setInterval(
this.loadCommentsFromServer.bind(this),
this.props.pollInterval
);
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm
@@ -566,14 +554,14 @@ var CommentForm = React.createClass({
},
render: function() {
return (
<form class="commentForm" onSubmit={this.handleSubmit}>
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" />
<input
type="text"
placeholder="Say something..."
ref="text"
/>
<input type="submit" />
<input type="submit" value="Post" />
</form>
);
}
@@ -588,8 +576,6 @@ var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -598,9 +584,8 @@ var CommentBox = React.createClass({
handleCommentSubmit: function(comment) {
$.ajax({
url: this.props.url,
type: 'POST',
data: comment,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -611,14 +596,11 @@ var CommentBox = React.createClass({
},
componentWillMount: function() {
this.loadCommentsFromServer();
setInterval(
this.loadCommentsFromServer.bind(this),
this.props.pollInterval
);
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm
@@ -640,8 +622,6 @@ var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -649,13 +629,12 @@ var CommentBox = React.createClass({
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
comments.push(comment);
this.setState({data: comments});
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
type: 'POST',
data: comment,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -666,14 +645,11 @@ var CommentBox = React.createClass({
},
componentWillMount: function() {
this.loadCommentsFromServer();
setInterval(
this.loadCommentsFromServer.bind(this),
this.props.pollInterval
);
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm

View File

@@ -28,6 +28,20 @@ The uncompressed, development version of React core with inline documentation.
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
```
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.min.js">React With Add-Ons {{site.react_version}} (production)</a>
The compressed, production version of React with [add-ons](/react/docs/addons.html).
```html
<script src="http://fb.me/react-with-addons-{{site.react_version}}.min.js"></script>
```
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.js">React With Add-Ons {{site.react_version}} (development)</a>
The uncompressed, development version of React with [add-ons](/react/docs/addons.html).
```html
<script src="http://fb.me/react-with-addons-{{site.react_version}}.js"></script>
```
#### <a href="http://fb.me/JSXTransformer-{{site.react_version}}.js">JSX Transform</a>
The JSX transformer used to support [XML syntax](/react/docs/jsx-in-depth.html) in JavaScript.

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.

After

Width:  |  Height:  |  Size: 168 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: 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

View File

@@ -7,23 +7,25 @@ id: home
<section class="light home-section">
<div class="marketing-row">
<div class="marketing-col">
<h3>Declarative</h3>
<h3>Just the UI</h3>
<p>
React uses a declarative paradigm that makes it easier to reason about
your application.
Lots of people use React as the V in MVC.
Since React makes no assumptions about the rest of your technology stack,
it&apos;s easy to try it out on a small feature in an existing project.
</p>
</div>
<div class="marketing-col">
<h3>Efficient</h3>
<h3>Virtual DOM</h3>
<p>
React computes the minimal set of changes necessary to keep your DOM
up-to-date.
React uses a <i>virtual DOM</i> diff implementation for ultra-high performance. It can also
render on the server using Node.js &mdash; no heavy browser DOM required.
</p>
</div>
<div class="marketing-col">
<h3>Flexible</h3>
<h3>Data flow</h3>
<p>
React works with the libraries and frameworks that you already know.
React implements one-way reactive data flow which reduces boilerplate and is
easier to reason about than traditional data binding.
</p>
</div>
</div>
@@ -60,7 +62,7 @@ id: home
This example uses `state` to track the current list of items as well as
the text that the user has entered. Although event handlers appear to be
rendered inline, they will be collected and implemented using event
delegation.
delegation.
</p>
<div id="todoExample"></div>
</div>

View File

@@ -0,0 +1,13 @@
---
id: introduction
title: Introduction
layout: tips
permalink: introduction.html
next: inline-styles.html
---
The React tips section provides bite-sized information that can answer lots of questions you might have and warn you against common pitfalls.
## Contributing
Submit a pull request to the [React repository](https://github.com/facebook/react) following the [current tips](https://github.com/facebook/react/tree/master/docs) entries' style. If you have a recipe that needs review prior to submitting a PR you can find help in the [#reactjs channel on freenode](irc://chat.freenode.net/reactjs) or the [reactjs Google group](http://groups.google.com/group/reactjs). Also, check the [Tips Wiki](https://github.com/facebook/react/wiki/Tips-(Previously-Cookbook)) for entries in-progress and general guidelines on writing React tips.

View File

@@ -0,0 +1,24 @@
---
id: inline-styles
title: Inline Styles
layout: tips
permalink: inline-styles.html
next: if-else-in-JSX.html
prev: introduction.html
---
In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string ([more on that later](/react/tips/style-props-value-px.html)):
```js
/** @jsx React.DOM */
var divStyle = {
color: 'white',
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all' // note the capital 'W' here
};
React.renderComponent(<div style={divStyle}>Hello World!</div>, mountNode);
```
Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. `node.style.backgroundImage`). Vendor prefixes should begin with a capital letter. This is why `WebkitTransition` has an uppercase "W".

View File

@@ -0,0 +1,42 @@
---
id: if-else-in-JSX
title: If-Else in JSX
layout: tips
permalink: if-else-in-JSX.html
prev: inline-styles.html
next: self-closing-tag.html
---
`if-else` statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. Take this basic example:
```js
/** @jsx React.DOM */
// This JSX:
React.renderComponent(<div id="msg">Hello World!</div>, mountNode);
// Is transformed to this JS:
React.renderComponent(React.DOM.div({id:"msg"}, "Hello World!"), mountNode);
```
This means that `if` statements don't fit in. Take this example:
```js
/** @jsx React.DOM */
// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>
// Is transformed to this JS:
React.DOM.div({id: if (condition) { 'msg' }}, "Hello World!");
```
That's not valid JS. You probably want to make use of a ternary expression:
```js
/** @jsx React.DOM */
React.renderComponent(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
```
Try using it today with the [JSX compiler](/react/jsx-compiler.html).

View File

@@ -0,0 +1,14 @@
---
id: self-closing-tag
title: Self-Closing Tag
layout: tips
permalink: self-closing-tag.html
prev: if-else-in-JSX.html
next: maximum-number-of-jsx-root-nodes.html
---
In JSX, `<MyComponent />` alone is valid while `<MyComponent>` isn't. All tags must be closed, either with the self-closing format or with a corresponding closing tag (`</MyComponent>`).
> Note:
>
> Every React component can be self-closing: `<div />`. `<div></div>` is also an equivalent.

View File

@@ -0,0 +1,12 @@
---
id: maximum-number-of-jsx-root-nodes
title: Maximum Number of JSX Root Nodes
layout: tips
permalink: maximum-number-of-jsx-root-nodes.html
prev: self-closing-tag.html
next: style-props-value-px.html
---
Currently, in a component's `render`, you can only return one node; if you have, say, a list of `div`s to return, you must wrap your components within a `div`, `span` or any other component.
Don't forget that JSX compiles into regular js; returning two functions doesn't really make syntactic sense. Likewise, don't put more than one child in a ternary.

View File

@@ -0,0 +1,29 @@
---
id: style-props-value-px
title: Shorthand for Specifying Pixel Values in style props
layout: tips
permalink: style-props-value-px.html
prev: maximum-number-of-jsx-root-nodes.html
next: children-props-type.html
---
When specifying a pixel value for your inline `style` prop, React automatically appends the string "px" for you after your number value, so this works:
```js
/** @jsx React.DOM */
var divStyle = {height: 10}; // rendered as "height:10px"
React.renderComponent(<div style={divStyle}>Hello World!</div>, mountNode);
```
See [Inline Styles](/react/tips/inline-styles.html) for more info.
Sometimes you _do_ want to keep the CSS properties unitless. Here's a list of properties that won't get the automatic "px" suffix:
- `fillOpacity`
- `fontWeight`
- `lineHeight`
- `opacity`
- `orphans`
- `zIndex`
- `zoom`

View File

@@ -0,0 +1,49 @@
---
id: children-props-type
title: Type of the Children props
layout: tips
permalink: children-props-type.html
prev: style-props-value-px.html
next: controlled-input-null-value.html
---
Usually, a component's children (`this.props.children`) is an array of components:
```js
/** @jsx React.DOM */
var GenericWrapper = React.createClass({
componentDidMount: function() {
console.log(Array.isArray(this.props.children)); // => true
},
render: function() {
return <div />;
}
});
React.renderComponent(
<GenericWrapper><span/><span/><span/></GenericWrapper>,
mountNode
);
```
However, when there is only a single child, `this.props.children` will be the single child component itself _without the array wrapper_. This saves an array allocation.
```js
/** @jsx React.DOM */
var GenericWrapper = React.createClass({
componentDidMount: function() {
console.log(Array.isArray(this.props.children)); // => false
// warning: yields 5 for length of the string 'hello', not 1 for the
// length of the non-existant array wrapper!
console.log(this.props.children.length);
},
render: function() {
return <div />;
}
});
React.renderComponent(<GenericWrapper>hello</GenericWrapper>, mountNode);
```

View File

@@ -0,0 +1,24 @@
---
id: controlled-input-null-value
title: Value of null for Controlled Input
layout: tips
permalink: controlled-input-null-value.html
prev: children-props-type.html
next: componentWillReceiveProps-not-triggered-after-mounting.html
---
Specifying the `value` prop on a [controlled component](/react/docs/forms.html) prevents the user from changing the input unless you desire so.
You might have run into a problem where `value` is specified, but the input can still be changed without consent. In this case, you might have accidentally set `value` to `undefined` or `null`.
The snippet below shows this phenomenon; after a second, the text becomes editable.
```js
/** @jsx React.DOM */
React.renderComponent(<input value="hi" />, mountNode);
setTimeout(function() {
React.renderComponent(<input value={null} />, mountNode);
}, 2000);
```

View File

@@ -0,0 +1,12 @@
---
id: componentWillReceiveProps-not-triggered-after-mounting
title: componentWillReceiveProps Not Triggered After Mounting
layout: tips
permalink: componentWillReceiveProps-not-triggered-after-mounting.html
prev: controlled-input-null-value.html
next: props-in-getInitialState-as-anti-pattern.html
---
`componentWillReceiveProps` isn't triggered after the node is put on scene. This is by design. Check out [other lifecycle methods](/react/docs/component-specs.html) for the one that suits your needs.
The reason for that is because `componentWillReceiveProps` often handles the logic of comparing with the old props and acting upon changes; not triggering it at mounting (where there are no old props) helps in defining what the method does.

View File

@@ -0,0 +1,62 @@
---
id: props-in-getInitialState-as-anti-pattern
title: Props in getInitialState Is an Anti-Pattern
layout: tips
permalink: props-in-getInitialState-as-anti-pattern.html
prev: componentWillReceiveProps-not-triggered-after-mounting.html
next: dom-event-listeners.html
---
> Note:
>
> This isn't really a React-specific tip, as such anti-patterns often occur in code in general; in this case, React simply points them out more clearly.
Using props, passed down from parent, to generate state in `getInitialState` often leads to duplication of "source of truth", i.e. where the real data is. Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.
Bad example:
```js
/** @jsx React.DOM */
var MessageBox = React.createClass({
getInitialState: function() {
return {nameWithQualifier: "Mr. " + this.props.name};
},
render: function() {
return <div>{this.state.nameWithQualifier}</div>;
}
});
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
```
Better:
```js
/** @jsx React.DOM */
var MessageBox = React.createClass({
render: function() {
return <div>{"Mr. " + this.props.name}</div>;
}
});
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
```
For more complex logic:
```js
/** @jsx React.DOM */
var MessageBox = React.createClass({
render: function() {
return <div>{this.getNameWithQualifier(this.props.name)}</div>;
},
getNameWithQualifier: function(name) {
return 'Mr. ' + name;
}
});
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
```

View File

@@ -0,0 +1,46 @@
---
id: dom-event-listeners
title: DOM Event Listeners in a Component
layout: tips
permalink: dom-event-listeners.html
prev: props-in-getInitialState-as-anti-pattern.html
next: initial-ajax.html
---
> Note:
>
> This entry shows how to attach DOM events not provided by React ([check here for more info](/react/docs/events.html)). This is good for integrations with other libraries such as jQuery.
Try to resize the window:
```js
/** @jsx React.DOM */
var Box = React.createClass({
getInitialState: function() {
return {windowWidth: window.innerWidth};
},
handleResize: function(e) {
this.setState({windowWidth: window.innerWidth});
},
componentDidMount: function() {
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleResize);
},
render: function() {
return <div>Current window width: {this.state.windowWidth}</div>;
}
});
React.renderComponent(<Box />, mountNode);
```
`componentDidMount` is called after the component is mounted and has a DOM representation. This is often a place where you would attach generic DOM events.
Notice that the event callback is bound to the react component and not the original element. React automatically binds methods to the current component instance for you through a process of [autobinding](../docs/interactivity-and-dynamic-uis.html#under-the-hood-autobinding-and-event-delegation).

View File

@@ -0,0 +1,47 @@
---
id: initial-ajax
title: Load Initial Data via AJAX
layout: tips
permalink: initial-ajax.html
prev: dom-event-listeners.html
next: false-in-jsx.html
---
Fetch data in `componentDidMount`. When the response arrives, store the data in state, triggering a render to update your UI.
This example fetches the desired Github user's latest gist:
```js
/** @jsx React.DOM */
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
var lastGist = result[0];
this.setState({
username: lastGist.user.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
React.renderComponent(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
```

View File

@@ -0,0 +1,33 @@
---
id: false-in-jsx
title: False in JSX
layout: tips
permalink: false-in-jsx.html
prev: initial-ajax.html
next: communicate-between-components.html
---
Here's how `false` renders in different contexts:
Renders as `id="false"`:
```js
/** @jsx React.DOM */
React.renderComponent(<div id={false} />, mountNode);
```
String "false" as input value:
```js
/** @jsx React.DOM */
React.renderComponent(<input value={false} />, mountNode);
```
No child:
```js
/** @jsx React.DOM */
React.renderComponent(<div>{false}</div>, mountNode);
```
The reason why this one doesn't render as the string `"false"` as a `div` child is to allow the more common use-case: `<div>{x > 1 && 'You have more than one item'}</div>`.

View File

@@ -0,0 +1,40 @@
---
id: communicate-between-components
title: Communicate Between Components
layout: tips
permalink: communicate-between-components.html
prev: false-in-jsx.html
---
For parent-child communication, simply [pass props](/react/docs/multiple-components.html).
For child-parent communication:
Say your `GroceryList` component has a list of items generated through an array. When a list item is clicked, you want to display its name:
```js
/** @jsx React.DOM */
var GroceryList = React.createClass({
handleClick: function(i) {
console.log('You clicked: ' + this.props.items[i]);
},
render: function() {
return (
<div>
{this.props.items.map(function(item, i) {
return (
<div onClick={this.handleClick.bind(this, i)} key={i}>{item}</div>
);
}, this)}
</div>
);
}
});
React.renderComponent(
<GroceryList items={['Apple', 'Banana', 'Cranberry']} />, mountNode
);
```
Notice the use of `bind(this, arg1, arg2, ...)`: we're simply passing more arguments to `handleClick`. This is not a new React concept; it's just JavaScript.

View File

@@ -20,7 +20,7 @@
.example-enter.example-enter-active,
.example-leave {
margin-left: 0;
opacity: 0.99;
opacity: 1;
}
.animateExample {

View File

@@ -3,6 +3,7 @@
'use strict';
var envify = require('envify/custom');
var grunt = require('grunt');
var UglifyJS = require('uglify-js');
@@ -59,12 +60,14 @@ var basic = {
outfile: './build/react.js',
debug: false,
standalone: 'React',
transforms: [envify({NODE_ENV: 'development'})],
after: [simpleBannerify]
};
var min = grunt.util._.merge({}, basic, {
outfile: './build/react.min.js',
debug: false,
transforms: [envify({NODE_ENV: 'production'})],
after: [minify, bannerify]
});
@@ -85,6 +88,7 @@ var addons = {
outfile: './build/react-with-addons.js',
debug: false,
standalone: 'React',
transforms: [envify({NODE_ENV: 'development'})],
packageName: 'React (with addons)',
after: [simpleBannerify]
};
@@ -92,6 +96,7 @@ var addons = {
var addonsMin = grunt.util._.merge({}, addons, {
outfile: './build/react-with-addons.min.js',
debug: false,
transforms: [envify({NODE_ENV: 'production'})],
after: [minify, bannerify]
});

View File

@@ -46,7 +46,7 @@ module.exports = function() {
};
// TODO: make sure this works, test with this too
config.transforms.forEach(bundle.transform, this);
config.transforms.forEach(bundle.transform, bundle);
// Actually bundle it up
var _this = this;

47
grunt/tasks/npm-react.js Normal file
View File

@@ -0,0 +1,47 @@
'use strict';
var grunt = require('grunt');
var src = 'npm-react/';
var dest = 'build/npm-react/';
var modSrc = 'build/modules/';
var lib = dest + 'lib/';
function buildRelease() {
// delete build/react-core for fresh start
grunt.file.exists(dest) && grunt.file.delete(dest);
// mkdir -p build/react-core/lib
grunt.file.mkdir(lib);
// Copy everything over
// console.log(grunt.file.expandMapping(src + '**/*', dest, {flatten: true}));
grunt.file.expandMapping(src + '**/*', dest, {flatten: true}).forEach(function(mapping) {
var src = mapping.src[0];
var dest = mapping.dest;
if (grunt.file.isDir(src)) {
grunt.file.mkdir(dest);
} else {
grunt.file.copy(src, dest);
}
});
// copy build/modules/*.js to build/react-core/lib
grunt.file.expandMapping(modSrc + '*.js', lib, { flatten: true }).forEach(function(mapping) {
grunt.file.copy(mapping.src[0], mapping.dest);
});
// modify build/react-core/package.json to set version ##
var pkg = grunt.file.readJSON(dest + 'package.json');
pkg.version = grunt.config.data.pkg.version;
grunt.file.write(dest + 'package.json', JSON.stringify(pkg, null, 2));
}
function buildDev() {
// TODO: same as above except different destination
}
module.exports = {
buildRelease: buildRelease,
buildDev: buildDev
};

View File

@@ -64,8 +64,8 @@ module.exports = function() {
var pkgDir = path.join(nodePath, pkg.name);
var doneCount = 2;
// Make sure that bin/jsx-internal is runnable by echoing main.js.
run("bin/jsx-internal", ["main.js"], {
// Make sure that bin/jsx is runnable by echoing main.js.
run("bin/jsx", ["main.js"], {
cwd: pkgDir
}, function(result) {
assert.ok(result.stdout.indexOf("transform") >= 0, result.stdout);

View File

@@ -22,7 +22,7 @@ module.exports = function() {
rootDirectory: config.rootDirectory,
args: args
}).then(function(output) {
grunt.file.write(config.outfile, output);
grunt.file.write(config.outfile, 'process = {env: {}};' + output);
done();
});
};

25
npm-react/README.md Normal file
View File

@@ -0,0 +1,25 @@
# react
An npm package to get you immediate access to [React](http://facebook.github.io/react/),
without also requiring the JSX transformer. This is especially useful for cases where you
want to [`browserify`](https://github.com/substack/node-browserify) your module using
`React`.
## 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 `autoflow` rather than `react`.
## Example Usage
```js
// Previously, you might access React with react-tools.
var React = require('react-tools').React;
// Now you can access React directly with react-core.
var React = require('react');
// You can also access ReactWithAddons.
var React = require('react/addons');
```

View File

@@ -0,0 +1,40 @@
'use strict';
var copyProperties = require('./lib/copyProperties');
var WARNING_MESSAGE = (
'It looks like you\'re trying to use jeffbski\'s React.js project.\n' +
'The `react` npm package now points to the React JavaScript library for ' +
'building user interfaces, not the React.js project for managing asynchronous ' +
'control flow. If you\'re looking for that library, please npm install autoflow.'
);
function error() {
throw new Error(WARNING_MESSAGE);
}
// Model the React.js project's public interface exactly.
function ReactJSShim() {
error();
}
ReactJSShim.logEvents = error;
ReactJSShim.resolvePromises = error;
ReactJSShim.trackTasks = error;
ReactJSShim.createEventCollector = error;
// These could throw using defineProperty() but supporting older browsers will
// be painful. Additionally any error messages around this will contain the string
// so I think this is sufficient.
ReactJSShim.options = WARNING_MESSAGE;
ReactJSShim.events = WARNING_MESSAGE;
var ReactJSErrors = {
wrap: function(module) {
copyProperties(ReactJSShim, module);
return ReactJSShim;
}
};
module.exports = ReactJSErrors;

4
npm-react/addons.js Normal file
View File

@@ -0,0 +1,4 @@
module.exports = require('./lib/ReactWithAddons');
if ('production' !== process.env.NODE_ENV) {
module.exports = require('./ReactJSErrors').wrap(module.exports);
}

36
npm-react/package.json Normal file
View File

@@ -0,0 +1,36 @@
{
"name": "react",
"version": "0.8.0",
"keywords": [
"react"
],
"homepage": "https://github.com/facebook/react/tree/master/npm-react",
"bugs": "https://github.com/facebook/react/issues?labels=react-core",
"licenses": [
{
"type": "Apache-2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
],
"files": [
"README.md",
"addons.js",
"react.js",
"ReactJSErrors.js",
"lib/"
],
"main": "react.js",
"repository": {
"type": "git",
"url": "https://github.com/facebook/react"
},
"engines": {
"node": ">=0.10.0"
},
"peerDependencies": {
"envify": "~0.2.0"
},
"browserify": {
"transform": ["envify"]
}
}

4
npm-react/react.js vendored Normal file
View File

@@ -0,0 +1,4 @@
module.exports = require('./lib/React');
if ('production' !== process.env.NODE_ENV) {
module.exports = require('./ReactJSErrors').wrap(module.exports);
}

1808
npm-shrinkwrap.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "react-tools",
"version": "0.5.0-alpha",
"version": "0.8.0",
"keywords": [
"react",
"jsx",
@@ -36,22 +36,23 @@
"test": "grunt build && grunt test"
},
"dependencies": {
"commoner": "~0.8.4",
"esprima-fb": "~1001.1001.2000-dev-harmony-fb",
"jstransform": "~1.0.1"
"commoner": "~0.8.8",
"esprima-fb": "~2001.1001.0-dev-harmony-fb",
"jstransform": "~2.0.1"
},
"devDependencies": {
"browserify": "~2.34.1",
"browserify": "~2.36.1",
"wrapup": "~0.12.0",
"populist": "~0.1.3",
"envify": "~0.2.0",
"populist": "~0.1.5",
"grunt-cli": "~0.1.9",
"grunt": "~0.4.1",
"grunt-contrib-copy": "~0.4.1",
"grunt-contrib-jshint": "~0.6.0",
"optimist": "~0.6.0",
"phantomjs": "~1.9.1-4",
"recast": "~0.4.16",
"semver": "~2.1.0",
"phantomjs": "~1.9",
"recast": "~0.4.24",
"semver": "~2.2.1",
"uglify-js": "~2.4.0",
"grunt-contrib-clean": "~0.5.0",
"grunt-compare-size": "~0.4.0",

View File

@@ -44,9 +44,10 @@ function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
for (var baseEventName in EVENT_NAME_MAP) {
for (var styleName in baseEventName) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(EVENT_NAME_MAP[styleName]);
endEvents.push(baseEvents[styleName]);
break;
}
}

View File

@@ -22,9 +22,24 @@ var React = require('React');
var ReactTransitionableChild = require('ReactTransitionableChild');
var ReactTransitionKeySet = require('ReactTransitionKeySet');
var invariant = require('invariant');
var ReactTransitionGroup = React.createClass({
propTypes: {
transitionName: React.PropTypes.string.isRequired,
transitionEnter: React.PropTypes.bool,
transitionLeave: React.PropTypes.bool,
onTransition: React.PropTypes.func,
component: React.PropTypes.func
},
getDefaultProps: function() {
return {
transitionEnter: true,
transitionLeave: true,
component: React.DOM.span
};
},
var ReactTransitionGroupMixin = {
componentWillMount: function() {
// _transitionGroupCurrentKeys stores the union of previous *and* next keys.
// If this were a component we'd store it as state, however, since this must
@@ -34,19 +49,19 @@ var ReactTransitionGroupMixin = {
this._transitionGroupCurrentKeys = {};
},
componentDidUpdate: function() {
if (this.props.onTransition) {
this.props.onTransition();
}
},
/**
* Render some children in a transitionable way.
*/
renderTransitionableChildren: function(sourceChildren) {
invariant(
this.getTransitionConfig,
'renderTransitionableChildren(): You must provide a ' +
'getTransitionConfig() method.'
);
var children = {};
var childMapping = ReactTransitionKeySet.getChildMapping(sourceChildren);
var transitionConfig = this.getTransitionConfig();
var currentKeys = ReactTransitionKeySet.mergeKeySets(
this._transitionGroupCurrentKeys,
ReactTransitionKeySet.getKeySet(sourceChildren)
@@ -58,10 +73,10 @@ var ReactTransitionGroupMixin = {
// may look up an old key in the new children, and it may switch to
// undefined. React's reconciler will keep the ReactTransitionableChild
// instance alive such that we can animate it.
if (childMapping[key] || transitionConfig.leave) {
if (childMapping[key] || this.props.transitionLeave) {
children[key] = ReactTransitionableChild({
name: transitionConfig.name,
enter: transitionConfig.enter,
name: this.props.transitionName,
enter: this.props.transitionEnter,
onDoneLeaving: this._handleDoneLeaving.bind(this, key)
}, childMapping[key]);
}
@@ -77,26 +92,6 @@ var ReactTransitionGroupMixin = {
// node.
delete this._transitionGroupCurrentKeys[key];
this.forceUpdate();
}
};
var ReactTransitionGroup = React.createClass({
mixins: [ReactTransitionGroupMixin],
getDefaultProps: function() {
return {
transitionEnter: true,
transitionLeave: true,
component: React.DOM.span
};
},
getTransitionConfig: function() {
return {
name: this.props.transitionName,
enter: this.props.transitionEnter,
leave: this.props.transitionLeave
};
},
render: function() {

View File

@@ -68,6 +68,9 @@ var ReactTransitionKeySet = {
* in `next` in a reasonable order.
*/
mergeKeySets: function(prev, next) {
prev = prev || {};
next = next || {};
var keySet = {};
var prevKeys = Object.keys(prev).concat([MERGE_KEY_SETS_TAIL_SENTINEL]);
var nextKeys = Object.keys(next).concat([MERGE_KEY_SETS_TAIL_SENTINEL]);

View File

@@ -26,18 +26,18 @@ var mocks;
// Most of the real functionality is covered in other unit tests, this just
// makes sure we're wired up correctly.
describe('ReactTransitionGroup', function() {
var container;
beforeEach(function() {
React = require('React');
ReactTransitionGroup = require('ReactTransitionGroup');
mocks = require('mocks');
container = document.createElement('div');
});
it('should warn after time with no transitionend', function() {
var container;
var a;
container = document.createElement('div');
a = React.renderComponent(
var a = React.renderComponent(
<ReactTransitionGroup transitionName="yolo">
<span key="one" id="one" />
</ReactTransitionGroup>,
@@ -65,7 +65,6 @@ describe('ReactTransitionGroup', function() {
});
it('should keep both sets of DOM nodes around', function() {
var container = document.createElement('div');
var a = React.renderComponent(
<ReactTransitionGroup transitionName="yolo">
<span key="one" id="one" />
@@ -83,4 +82,14 @@ describe('ReactTransitionGroup', function() {
expect(a.getDOMNode().childNodes[0].id).toBe('two');
expect(a.getDOMNode().childNodes[1].id).toBe('one');
});
describe('with an undefined child', function () {
it('should fail silently', function () {
React.renderComponent(
<ReactTransitionGroup transitionName="yolo">
</ReactTransitionGroup>,
container
);
});
});
});

View File

@@ -127,4 +127,30 @@ describe('ReactTransitionKeySet', function() {
five: true
});
});
it('should support mergeKeySets with undefined input', function () {
var prev = {
one: true,
two: true
};
var next = undefined;
expect(ReactTransitionKeySet.mergeKeySets(prev, next)).toEqual({
one: true,
two: true
});
prev = undefined;
next = {
three: true,
four: true
};
expect(ReactTransitionKeySet.mergeKeySets(prev, next)).toEqual({
three: true,
four: true
});
});
});

View File

@@ -66,6 +66,6 @@ var React = {
// Version exists only in the open-source version of React, not in Facebook's
// internal version.
React.version = '0.5.0-alpha';
React.version = '0.8.0';
module.exports = React;

View File

@@ -127,8 +127,8 @@ function validateChildKeys(component) {
* `mountComponent`
* Initializes the component, renders markup, and registers event listeners.
*
* `receiveProps`
* Updates the rendered DOM nodes given a new set of props.
* `receiveComponent`
* Updates the rendered DOM nodes to match the given component.
*
* `unmountComponent`
* Releases any resources allocated by this component.
@@ -151,7 +151,7 @@ var ReactComponent = {
return !!(
object &&
typeof object.mountComponentIntoNode === 'function' &&
typeof object.receiveProps === 'function'
typeof object.receiveComponent === 'function'
);
},
@@ -369,21 +369,22 @@ var ReactComponent = {
},
/**
* Updates the rendered DOM nodes given a new set of props.
* Given a new instance of this component, updates the rendered DOM nodes
* as if that instance was rendered instead.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.receiveProps.call(this, ...)`.
* `ReactComponent.Mixin.receiveComponent.call(this, ...)`.
*
* @param {object} nextProps Next set of properties.
* @param {object} nextComponent Next set of properties.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveProps: function(nextProps, transaction) {
receiveComponent: function(nextComponent, transaction) {
invariant(
this.isMounted(),
'receiveProps(...): Can only update a mounted component.'
'receiveComponent(...): Can only update a mounted component.'
);
this._pendingProps = nextProps;
this._pendingProps = nextComponent.props;
this._performUpdateIfNecessary(transaction);
},

View File

@@ -20,6 +20,7 @@
var ReactComponent = require('ReactComponent');
var ReactCurrentOwner = require('ReactCurrentOwner');
var ReactErrorUtils = require('ReactErrorUtils');
var ReactOwner = require('ReactOwner');
var ReactPerf = require('ReactPerf');
var ReactPropTransferer = require('ReactPropTransferer');
@@ -326,11 +327,14 @@ function validateLifeCycleOnReplaceState(instance) {
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted or mounting component.'
);
invariant(
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component or during ' +
'an existing state transition (such as within `render`).'
invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE,
'replaceState(...): Cannot update during an existing state transition ' +
'(such as within `render`). This could potentially cause an infinite ' +
'loop so it is forbidden.'
);
invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component. This ' +
'usually means you called setState() on an unmounted component.'
);
}
@@ -792,7 +796,7 @@ var ReactCompositeComponentMixin = {
var currentComponent = this._renderedComponent;
var nextComponent = this._renderValidatedComponent();
if (currentComponent.constructor === nextComponent.constructor) {
currentComponent.receiveProps(nextComponent.props, transaction);
currentComponent.receiveComponent(nextComponent, transaction);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
@@ -860,7 +864,8 @@ var ReactCompositeComponentMixin = {
}
invariant(
ReactComponent.isValidComponent(renderedComponent),
'%s.render(): A valid ReactComponent must be returned.',
'%s.render(): A valid ReactComponent must be returned. You may have ' +
'returned null, undefined, an array, or some other invalid object.',
this.constructor.displayName || 'ReactCompositeComponent'
);
return renderedComponent;
@@ -875,7 +880,10 @@ var ReactCompositeComponentMixin = {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(method);
this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard(
method,
this.constructor.displayName + '.' + autoBindKey
));
}
},

View File

@@ -179,9 +179,13 @@ ReactDOMComponent.Mixin = {
return '';
},
receiveProps: function(nextProps, transaction) {
assertValidProps(nextProps);
ReactComponent.Mixin.receiveProps.call(this, nextProps, transaction);
receiveComponent: function(nextComponent, transaction) {
assertValidProps(nextComponent.props);
ReactComponent.Mixin.receiveComponent.call(
this,
nextComponent,
transaction
);
},
/**

View File

@@ -102,25 +102,6 @@ var ReactDOMIDOperations = {
DOMPropertyOperations.deleteValueForProperty(node, name, value);
},
/**
* This should almost never be used instead of `updatePropertyByID()` due to
* the extra object allocation required by the API. That said, this is useful
* for batching up several operations across worker thread boundaries.
*
* @param {string} id ID of the node to update.
* @param {object} properties A mapping of valid property names.
* @internal
* @see {ReactDOMIDOperations.updatePropertyByID}
*/
updatePropertiesByID: function(id, properties) {
for (var name in properties) {
if (!properties.hasOwnProperty(name)) {
continue;
}
ReactDOMIDOperations.updatePropertiesByID(id, name, properties[name]);
}
},
/**
* Updates a DOM node with new style values. If a value is specified as '',
* the corresponding style property will be unset.

View File

@@ -137,7 +137,15 @@ function setModernOffsets(node, offsets) {
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = typeof offsets.end === 'undefined' ?
start : Math.min(offsets.end, length);
start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
@@ -146,8 +154,15 @@ function setModernOffsets(node, offsets) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
range.detach();
}
}

View File

@@ -241,6 +241,7 @@ var ReactEventEmitter = merge(ReactEventEmitterMixin, {
trapBubbledEvent(topLevelTypes.topMouseOut, 'mouseout', mountAt);
trapBubbledEvent(topLevelTypes.topClick, 'click', mountAt);
trapBubbledEvent(topLevelTypes.topDoubleClick, 'dblclick', mountAt);
trapBubbledEvent(topLevelTypes.topContextMenu, 'contextmenu', mountAt);
if (touchNotMouse) {
trapBubbledEvent(topLevelTypes.topTouchStart, 'touchstart', mountAt);
trapBubbledEvent(topLevelTypes.topTouchEnd, 'touchend', mountAt);

View File

@@ -20,11 +20,11 @@
var ReactDOMSelection = require('ReactDOMSelection');
var containsNode = require('containsNode');
var getActiveElement = require('getActiveElement');
var nodeContains = require('nodeContains');
function isInDocument(node) {
return nodeContains(document.documentElement, node);
return containsNode(document.documentElement, node);
}
/**

View File

@@ -22,9 +22,9 @@ var ReactEventEmitter = require('ReactEventEmitter');
var ReactInstanceHandles = require('ReactInstanceHandles');
var $ = require('$');
var containsNode = require('containsNode');
var getReactRootElementInContainer = require('getReactRootElementInContainer');
var invariant = require('invariant');
var nodeContains = require('nodeContains');
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
@@ -141,7 +141,7 @@ function isValid(node, id) {
);
var container = ReactMount.findReactContainerForID(id);
if (container && nodeContains(container, node)) {
if (container && containsNode(container, node)) {
return true;
}
}
@@ -430,6 +430,10 @@ var ReactMount = {
unmountComponentFromNode: function(instance, container) {
instance.unmountComponent();
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
@@ -592,6 +596,8 @@ var ReactMount = {
ATTR_NAME: ATTR_NAME,
getReactRootID: getReactRootID,
getID: getID,
setID: setID,

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