Compare commits
59 Commits
v0.9.0
...
0.5-stable
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b809ffbc4 | ||
|
|
e6912a7a4a | ||
|
|
f1ae3392bd | ||
|
|
94a9a3e752 | ||
|
|
48af9c7bda | ||
|
|
1da10d718d | ||
|
|
ef8bd04b04 | ||
|
|
030835b914 | ||
|
|
abf199d5ff | ||
|
|
1053a1453a | ||
|
|
b8194d92f6 | ||
|
|
18a6b0b94b | ||
|
|
0b31175238 | ||
|
|
6a0bb61b16 | ||
|
|
c065b03b8a | ||
|
|
c32c788e5a | ||
|
|
4a0a14d319 | ||
|
|
a55d44efaf | ||
|
|
08fcec503c | ||
|
|
cd6d43e4c0 | ||
|
|
c329eb6335 | ||
|
|
215988f879 | ||
|
|
fb7e157cba | ||
|
|
8ead6dce76 | ||
|
|
79b09d9597 | ||
|
|
fb1a072739 | ||
|
|
c1c7a601dd | ||
|
|
adad0d72be | ||
|
|
e7f48a6c00 | ||
|
|
d3cee1ee2e | ||
|
|
d47d509637 | ||
|
|
411419c361 | ||
|
|
fc67d5544c | ||
|
|
4faad1a32a | ||
|
|
01b40d84c7 | ||
|
|
67d0f15d1a | ||
|
|
e5f03ae407 | ||
|
|
25140e5a0d | ||
|
|
b5804fa565 | ||
|
|
1bb2651660 | ||
|
|
b21cdac9e3 | ||
|
|
92ce80cf4f | ||
|
|
f3db0006e8 | ||
|
|
ef4d7a37f0 | ||
|
|
64016811d3 | ||
|
|
7b957c880c | ||
|
|
1b835fb5cf | ||
|
|
9f0bbce797 | ||
|
|
c9d20e56d3 | ||
|
|
ce612904ef | ||
|
|
ea1ab5501d | ||
|
|
2c35ed8068 | ||
|
|
c994cc24c3 | ||
|
|
24da1c0023 | ||
|
|
d82181e4b9 | ||
|
|
ba166b9652 | ||
|
|
f756cb3d9c | ||
|
|
cadf8b786c | ||
|
|
953947a617 |
@@ -2,13 +2,11 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
max_line_length = 80
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
max_line_length = 0
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
1
.gitattributes
vendored
@@ -1 +0,0 @@
|
||||
* text=auto
|
||||
12
.gitignore
vendored
@@ -13,9 +13,13 @@ docs/code
|
||||
docs/_site
|
||||
docs/.sass-cache
|
||||
docs/css/react.css
|
||||
docs/js/*
|
||||
docs/js/.module-cache
|
||||
docs/js/JSXTransformer.js
|
||||
docs/js/react.min.js
|
||||
docs/js/docs.js
|
||||
docs/js/jsx-compiler.js
|
||||
docs/js/live_editor.js
|
||||
docs/js/examples
|
||||
docs/downloads
|
||||
examples/shared/*.js
|
||||
test/the-files-to-test.generated.js
|
||||
*.log*
|
||||
chrome-user-data
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
"noempty": true,
|
||||
"nonstandard": true,
|
||||
"onecase": true,
|
||||
"sub": true,
|
||||
"regexdash": true,
|
||||
"trailing": true,
|
||||
"undef": true,
|
||||
|
||||
22
.mailmap
@@ -1,41 +1,21 @@
|
||||
Ben Newman <bn@cs.stanford.edu> <benjamn@fb.com>
|
||||
Cheng Lou <chenglou92@gmail.com> <chenglou@fb.com>
|
||||
Christoph Pojer <christoph.pojer@gmail.com>
|
||||
Christoph Pojer <christoph.pojer@gmail.com> <cpojer@fb.com>
|
||||
Connor McSheffrey <c@conr.me> <connor.mcsheffrey@gmail.com>
|
||||
Dan Schafer <dschafer@fb.com>
|
||||
Fabio M. Costa <fabiomcosta@gmail.com> <fabs@fb.com>
|
||||
Harry Hull <harry.hull1@gmail.com>
|
||||
Ingvar Stepanyan <me@rreverser.com> <rreverser@ubuntu.rreverser.a4.internal.cloudapp.net>
|
||||
Jason Bonta <jbonta@gmail.com> <jasonbonta@fb.com>
|
||||
Jason Trill <jason@jasontrill.com>
|
||||
Jeff Morrison <jeff@anafx.com> <Jeff@anafx.com>
|
||||
Jeff Morrison <jeff@anafx.com> <jeffmo@fb.com>
|
||||
Jeff Morrison <jeff@anafx.com> JeffMo <jeffmo@fb.com>
|
||||
Jeffrey Lin <lin.jeffrey@gmail.com> <jeffreylin@fb.com>
|
||||
Jonathan Hsu <jhiswin@gmail.com>
|
||||
Jordan Walke <jordojw@gmail.com>
|
||||
Jordan Walke <jordojw@gmail.com> <jordanjcw@fb.com>
|
||||
Josh Duck <josh@fb.com> <github@joshduck.com>
|
||||
Jun Wu <quark@lihdd.net>
|
||||
Keito Uchiyama <projects@keito.me> <keito@fb.com>
|
||||
Laurence Rowe <l@lrowe.co.uk> <laurence@lrowe.co.uk>
|
||||
Martin Andert <mandert@gmail.com>
|
||||
Michal Srb <xixixao@seznam.cz> xixixao <xixixao@seznam.cz>
|
||||
Nick Gavalas <njg57@cornell.edu>
|
||||
Nick Thompson <ncthom91@gmail.com> <nickt@instagram.com>
|
||||
Paul O’Shannessy <paul@oshannessy.com> <poshannessy@fb.com>
|
||||
Paul Shen <paul@mnml0.com> <paulshen@fb.com>
|
||||
Pete Hunt <floydophone@gmail.com>
|
||||
Pete Hunt <floydophone@gmail.com> <pete.hunt@fb.com>
|
||||
Pete Hunt <floydophone@gmail.com> <pete@instagram.com>
|
||||
Pete Hunt <floydophone@gmail.com> <phunt@instagram.com>
|
||||
Pieter Vanderwerff <me@pieter.io> <pieter@heyday.co.nz>
|
||||
Richard Feldman <richard.t.feldman@gmail.com> <richard@noredink.com>
|
||||
Richard Livesey <Livesey7@hotmail.co.uk>
|
||||
Sander Spies <sandermail@gmail.com>
|
||||
Sebastian Markbåge <sebastian@calyptus.eu> <sema@fb.com>
|
||||
Stoyan Stefanov <ssttoo@ymail.com>
|
||||
Thomas Aylott <oblivious@subtlegradient.com> <aylott@fb.com>
|
||||
Timothy Yung <yungsters@gmail.com> <yungsters@fb.com>
|
||||
Vjeux <vjeuxx@gmail.com>
|
||||
Vjeux <vjeuxx@gmail.com> <vjeux@fb.com>
|
||||
|
||||
56
.travis.yml
@@ -2,62 +2,14 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- '0.10'
|
||||
script:
|
||||
- |
|
||||
grunt $TEST_TYPE
|
||||
after_script:
|
||||
- |
|
||||
if [ "$TEST_TYPE" = test:full ] && [ "$SERVER" ]; then
|
||||
grunt build
|
||||
curl \
|
||||
-F "react=@build/react.js" \
|
||||
-F "react.min=@build/react.min.js" \
|
||||
-F "transformer=@build/JSXTransformer.js" \
|
||||
-F "react-with-addons=@build/react-with-addons.js" \
|
||||
-F "react-with-addons.min=@build/react-with-addons.min.js" \
|
||||
-F "npm-react=@build/react.tgz" \
|
||||
-F "npm-react-tools=@build/react-tools.tgz" \
|
||||
-F "commit=$TRAVIS_COMMIT" \
|
||||
-F "date=`git log --format='%ct' -1`" \
|
||||
-F "pull_request=$TRAVIS_PULL_REQUEST" \
|
||||
-F "token=$SECRET_TOKEN" \
|
||||
-F "branch=$TRAVIS_BRANCH" \
|
||||
$SERVER
|
||||
fi
|
||||
- curl -F "react=@build/react.js" -F "react.min=@build/react.min.js" -F "transformer=@build/JSXTransformer.js"
|
||||
-F "react-with-addons=@build/react-with-addons.js" -F "react-with-addons.min=@build/react-with-addons.min.js"
|
||||
-F "commit=$TRAVIS_COMMIT" -F "date=`git log --format='%ct' -1`" -F "pull_request=$TRAVIS_PULL_REQUEST"
|
||||
-F "token=$SECRET_TOKEN" -F "branch=$TRAVIS_BRANCH" $SERVER
|
||||
env:
|
||||
matrix:
|
||||
- TEST_TYPE=test:full
|
||||
- TEST_TYPE=lint
|
||||
- TEST_TYPE=perf:full
|
||||
- TEST_TYPE=test:coverage
|
||||
- TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=ie11
|
||||
- TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=ie10
|
||||
- TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=ie9
|
||||
- TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=ie8
|
||||
- TEST_TYPE=test:webdriver:saucelabs:ios
|
||||
- TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=safari
|
||||
global:
|
||||
# SERVER
|
||||
- secure: qPvsJ46XzGrdIuPA70b55xQNGF8jcK7N1LN5CCQYYocXLa+fBrl+fTE77QvehOPhqwJXcj6kOxI+sY0KrVwV7gmq2XY2HZGWUSCxTN0SZlNIzqPA80Y7G/yOjA4PUt8LKgP+8tptyhTAY56qf+hgW8BoLiKOdztYF2p+3zXOLuA=
|
||||
# SECRET_TOKEN
|
||||
- secure: dkpPW+VnoqC/okhRdV90m36NcyBFhcwEKL3bNFExAwi0dXnFao8RoFlvnwiPlA23h2faROkMIetXlti6Aju08BgUFV+f9aL6vLyU7gUent4Nd3413zf2fwDtXIWIETg6uLnOpSykGKgCAT/hY3Q2oPLqOoY0OxfgnbqwxkxljrE=
|
||||
matrix:
|
||||
fast_finish: true
|
||||
allow_failures:
|
||||
- env: TEST_TYPE=lint
|
||||
- env: TEST_TYPE=test:coverage
|
||||
- env: TEST_TYPE=perf:full
|
||||
- env: TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=ie11
|
||||
- env: TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=ie10
|
||||
- env: TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=ie9
|
||||
- env: TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=ie8
|
||||
- env: TEST_TYPE=test:webdriver:saucelabs:ios
|
||||
- env: TEST_TYPE=test:webdriver:saucelabs BROWSER_NAME=safari
|
||||
notifications:
|
||||
irc:
|
||||
use_notice: true
|
||||
skip_join: true
|
||||
on_success: change
|
||||
on_failure: change
|
||||
channels:
|
||||
- chat.freenode.net#reactjs
|
||||
|
||||
62
AUTHORS
@@ -1,108 +1,50 @@
|
||||
Alan deLevie <adelevie@gmail.com>
|
||||
Alex Zelenskiy <azelenskiy@fb.com>
|
||||
Alexander Solovyov <alexander@solovyov.net>
|
||||
Andreas Svensson <andreas@syranide.com>
|
||||
Andrew Davey <andrew@equin.co.uk>
|
||||
Andrew Zich <azich@fb.com>
|
||||
Andrey Popp <8mayday@gmail.com>
|
||||
Ayman Osman <aymano.osman@gmail.com>
|
||||
Ben Alpert <spicyjalapeno@gmail.com>
|
||||
Ben Newman <bn@cs.stanford.edu>
|
||||
Ben Ripkens <bripkens.dev@gmail.com>
|
||||
Bob Eagan <bob@synapsestudios.com>
|
||||
Brian Cooke <bri@bricooke.com>
|
||||
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 <christoph.pojer@gmail.com>
|
||||
Clay Allsopp <clay.allsopp@gmail.com>
|
||||
Connor McSheffrey <c@conr.me>
|
||||
Connor McSheffrey <connor.mcsheffrey@gmail.com>
|
||||
Dan Schafer <dschafer@fb.com>
|
||||
Daniel Gasienica <dgasienica@zynga.com>
|
||||
Daniel Lo Nigro <danlo@fb.com>
|
||||
Daniel Miladinov <dmiladinov@wingspan.com>
|
||||
Danny Ben-David <dannybd@fb.com>
|
||||
David Hellsing <david@aino.se>
|
||||
David Hu <davidhu91@gmail.com>
|
||||
Dustin Getz <dgetz@wingspan.com>
|
||||
Eric Clemmons <eric@smarterspam.com>
|
||||
Eric Schoffstall <contra@wearefractal.com>
|
||||
Fabio M. Costa <fabiomcosta@gmail.com>
|
||||
Felipe Oliveira Carvalho <felipekde@gmail.com>
|
||||
Felix Kling <fkling@fb.com>
|
||||
Fernando Correia <fernando@servicero.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>
|
||||
Ingvar Stepanyan <me@rreverser.com>
|
||||
Isaac Salier-Hellendag <isaac@fb.com>
|
||||
Ivan Kozik <ivan@ludios.org>
|
||||
Jakub Malinowski <jakubmal@gmail.com>
|
||||
James Ide <ide@fb.com>
|
||||
Jamie Wong <jamie.lf.wong@gmail.com>
|
||||
Jamison Dance <jergason@gmail.com>
|
||||
Jan Kassens <jkassens@fb.com>
|
||||
Jared Forsyth <jared@jaredforsyth.com>
|
||||
Jason Bonta <jbonta@gmail.com>
|
||||
Jason Trill <jason@jasontrill.com>
|
||||
Jean Lauliac <lauliacj@gmail.com>
|
||||
Jeff Morrison <jeff@anafx.com>
|
||||
Jeffrey Lin <lin.jeffrey@gmail.com>
|
||||
Jignesh Kakadiya <jigneshhk1992@gmail.com>
|
||||
Johannes Baiter <johannes.baiter@gmail.com>
|
||||
John Watson <jwatson@fb.com>
|
||||
Jonas Gebhardt <jonas@instagram.com>
|
||||
Jonathan Hsu <jhiswin@gmail.com>
|
||||
Jordan Walke <jordojw@gmail.com>
|
||||
Josh Duck <josh@fb.com>
|
||||
Jun Wu <quark@lihdd.net>
|
||||
Keito Uchiyama <projects@keito.me>
|
||||
Kit Randel <kit@nocturne.net.nz>
|
||||
Keito Uchiyama <keito@fb.com>
|
||||
Kunal Mehta <k.mehta@berkeley.edu>
|
||||
Laurence Rowe <l@lrowe.co.uk>
|
||||
Levi McCallum <levi@levimccallum.com>
|
||||
Logan Allen <loganfynne@gmail.com>
|
||||
Luigy Leon <luichi.19@gmail.com>
|
||||
Mark Richardson <echo@fb.com>
|
||||
Marshall Roch <mroch@fb.com>
|
||||
Martin Andert <mandert@gmail.com>
|
||||
Martin Konicek <mkonicek@fb.com>
|
||||
Mathieu M-Gosselin <mathieumg@gmail.com>
|
||||
Matt Harrison <mt.harrison86@gmail.com>
|
||||
Matti Nelimarkka <matti.nelimarkka@hiit.fi>
|
||||
Michal Srb <xixixao@seznam.cz>
|
||||
Mouad Debbar <mdebbar@fb.com>
|
||||
Nadeesha Cabral <nadeesha.cabral@gmail.com>
|
||||
Nicholas Bergson-Shilcock <me@nicholasbs.net>
|
||||
Nick Gavalas <njg57@cornell.edu>
|
||||
Nick Thompson <ncthom91@gmail.com>
|
||||
Owen Coutts <owenc@fb.com>
|
||||
Pascal Hartig <passy@twitter.com>
|
||||
Paul O’Shannessy <paul@oshannessy.com>
|
||||
Paul Seiffert <paul.seiffert@gmail.com>
|
||||
Paul Shen <paul@mnml0.com>
|
||||
Pete Hunt <floydophone@gmail.com>
|
||||
Peter Cottle <pcottle@fb.com>
|
||||
Pieter Vanderwerff <me@pieter.io>
|
||||
Richard D. Worth <rdworth@gmail.com>
|
||||
Richard Feldman <richard.t.feldman@gmail.com>
|
||||
Richard Livesey <Livesey7@hotmail.co.uk>
|
||||
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 <oblivious@subtlegradient.com>
|
||||
Timothy Yung <yungsters@gmail.com>
|
||||
Tom Occhino <tomocchino@gmail.com>
|
||||
Vjeux <vjeuxx@gmail.com>
|
||||
Wincent Colaiuta <win@wincent.com>
|
||||
Zach Bruggeman <zbruggeman@me.com>
|
||||
imagentleman <imagentlemail@gmail.com>
|
||||
plievone <plievone@cc.hut.fi>
|
||||
|
||||
109
CHANGELOG.md
@@ -1,112 +1,3 @@
|
||||
## 0.9.0 (February 20, 2014)
|
||||
|
||||
### React Core
|
||||
|
||||
#### Breaking Changes
|
||||
|
||||
- The lifecycle methods `componentDidMount` and `componentDidUpdate` no longer receive the root node as a parameter; use `this.getDOMNode()` instead
|
||||
- Whenever a prop is equal to `undefined`, the default value returned by `getDefaultProps` will now be used instead
|
||||
- `React.unmountAndReleaseReactRootNode` was previously deprecated and has now been removed
|
||||
- `React.renderComponentToString` is now synchronous and returns the generated HTML string
|
||||
- Full-page rendering (that is, rendering the `<html>` tag using React) is now supported only when starting with server-rendered markup
|
||||
- On mouse wheel events, `deltaY` is no longer negated
|
||||
- When prop types validation fails, a warning is logged instead of an error thrown (with the production build of React, type checks are now skipped for performance)
|
||||
- On `input`, `select`, and `textarea` elements, `.getValue()` is no longer supported; use `.getDOMNode().value` instead
|
||||
|
||||
#### New Features
|
||||
|
||||
- React now never rethrows errors, so stack traces are more accurate and Chrome's purple break-on-error stop sign now works properly
|
||||
- Added support for SVG tags `defs`, `linearGradient`, `polygon`, `radialGradient`, `stop`
|
||||
- Added support for more attributes:
|
||||
- `crossOrigin` for CORS requests
|
||||
- `download` and `hrefLang` for `<a>` tags
|
||||
- `mediaGroup` and `muted` for `<audio>` and `<video>` tags
|
||||
- `noValidate` and `formNoValidate` for forms
|
||||
- `property` for Open Graph `<meta>` tags
|
||||
- `sandbox`, `seamless`, and `srcDoc` for `<iframe>` tags
|
||||
- `scope` for screen readers
|
||||
- `span` for `<colgroup>` tags
|
||||
- Added support for defining `propTypes` in mixins
|
||||
- Added `any`, `arrayOf`, `component`, `oneOfType`, `renderable`, `shape` to `React.PropTypes`
|
||||
- Added support for `statics` on component spec for static component methods
|
||||
- On all events, `.currentTarget` is now properly set
|
||||
- On keyboard events, `.key` is now polyfilled in all browsers for special (non-printable) keys
|
||||
- On clipboard events, `.clipboardData` is now polyfilled in IE
|
||||
- On drag events, `.dragTransfer` is now present
|
||||
- Added support for `onMouseOver` and `onMouseOut` in addition to the existing `onMouseEnter` and `onMouseLeave` events
|
||||
- Added support for `onLoad` and `onError` on `<img>` elements
|
||||
- Added support for `onReset` on `<form>` elements
|
||||
- The `autoFocus` attribute is now polyfilled consistently on `input`, `select`, and `textarea`
|
||||
|
||||
#### Bug Fixes
|
||||
|
||||
- React no longer adds an `__owner__` property to each component's `props` object; passed-in props are now never mutated
|
||||
- When nesting top-level components (e.g., calling `React.renderComponent` within `componentDidMount`), events now properly bubble to the parent component
|
||||
- Fixed a case where nesting top-level components would throw an error when updating
|
||||
- Passing an invalid or misspelled propTypes type now throws an error
|
||||
- On mouse enter/leave events, `.target`, `.relatedTarget`, and `.type` are now set properly
|
||||
- On composition events, `.data` is now properly normalized in IE9 and IE10
|
||||
- CSS property values no longer have `px` appended for the unitless properties `columnCount`, `flex`, `flexGrow`, `flexShrink`, `lineClamp`, `order`, `widows`
|
||||
- Fixed a memory leak when unmounting children with a `componentWillUnmount` handler
|
||||
- Fixed a memory leak when `renderComponentToString` would store event handlers
|
||||
- Fixed an error that could be thrown when removing form elements during a click handler
|
||||
- Boolean attributes such as `disabled` are rendered without a value (previously `disabled="true"`, now simply `disabled`)
|
||||
- `key` values containing `.` are now supported
|
||||
- Shortened `data-reactid` values for performance
|
||||
- Components now always remount when the `key` property changes
|
||||
- Event handlers are attached to `document` only when necessary, improving performance in some cases
|
||||
- Events no longer use `.returnValue` in modern browsers, eliminating a warning in Chrome
|
||||
- `scrollLeft` and `scrollTop` are no longer accessed on document.body, eliminating a warning in Chrome
|
||||
- General performance fixes, memory optimizations, improvements to warnings and error messages
|
||||
|
||||
### React with Addons
|
||||
|
||||
- `React.addons.TestUtils` was added to help write unit tests
|
||||
- `React.addons.TransitionGroup` was renamed to `React.addons.CSSTransitionGroup`
|
||||
- `React.addons.TransitionGroup` was added as a more general animation wrapper
|
||||
- `React.addons.cloneWithProps` was added for cloning components and modifying their props
|
||||
- Bug fix for adding back nodes during an exit transition for CSSTransitionGroup
|
||||
- Bug fix for changing `transitionLeave` in CSSTransitionGroup
|
||||
- Performance optimizations for CSSTransitionGroup
|
||||
- On checkbox `<input>` elements, `checkedLink` is now supported for two-way binding
|
||||
|
||||
### JSX Compiler and react-tools Package
|
||||
|
||||
- Whitespace normalization has changed; now space between two tags on the same line will be preserved, while newlines between two tags will be removed
|
||||
- The `react-tools` npm package no longer includes the React core libraries; use the `react` package instead.
|
||||
- `displayName` is now added in more cases, improving error messages and names in the React Dev Tools
|
||||
- Fixed an issue where an invalid token error was thrown after a JSX closing tag
|
||||
- `JSXTransformer` now uses source maps automatically in modern browsers
|
||||
- `JSXTransformer` error messages now include the filename and problematic line contents when a file fails to parse
|
||||
|
||||
## 0.8.0 (December 19, 2013)
|
||||
|
||||
### React
|
||||
|
||||
* Added support for more attributes:
|
||||
* `rows` & `cols` for `<textarea>`
|
||||
* `defer` & `async` for `<script>`
|
||||
* `loop` for `<audio>` & `<video>`
|
||||
* `autoCorrect` for form fields (a non-standard attribute only supported by mobile WebKit)
|
||||
* Improved error messages
|
||||
* Fixed Selection events in IE11
|
||||
* Added `onContextMenu` events
|
||||
|
||||
### React with Addons
|
||||
|
||||
* Fixed bugs with TransitionGroup when children were undefined
|
||||
* Added support for `onTransition`
|
||||
|
||||
### react-tools
|
||||
|
||||
* Upgraded `jstransform` and `esprima-fb`
|
||||
|
||||
### JSXTransformer
|
||||
|
||||
* Added support for use in IE8
|
||||
* Upgraded browserify, which reduced file size by ~65KB (16KB gzipped)
|
||||
|
||||
|
||||
## 0.5.2, 0.4.2 (December 18, 2013)
|
||||
|
||||
### React
|
||||
|
||||
@@ -57,7 +57,6 @@ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
|
||||
* `"use strict";`
|
||||
* 80 character line length
|
||||
* "Attractive"
|
||||
* Do not use the optional parameters of `setTimeout` and `setInterval`
|
||||
|
||||
## License
|
||||
|
||||
|
||||
189
Gruntfile.js
@@ -3,200 +3,97 @@
|
||||
var exec = require('child_process').exec;
|
||||
var jsxTask = require('./grunt/tasks/jsx');
|
||||
var browserifyTask = require('./grunt/tasks/browserify');
|
||||
var wrapupTask = require('./grunt/tasks/wrapup');
|
||||
var populistTask = require('./grunt/tasks/populist');
|
||||
var webdriverPhantomJSTask = require('./grunt/tasks/webdriver-phantomjs');
|
||||
var webdriverJasmineTasks = require('./grunt/tasks/webdriver-jasmine');
|
||||
var sauceTunnelTask = require('./grunt/tasks/sauce-tunnel');
|
||||
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');
|
||||
var npmReactToolsTasks = require('./grunt/tasks/npm-react-tools');
|
||||
var versionCheckTask = require('./grunt/tasks/version-check');
|
||||
|
||||
module.exports = function(grunt) {
|
||||
|
||||
grunt.initConfig({
|
||||
pkg: grunt.file.readJSON('package.json'),
|
||||
copy: require('./grunt/config/copy'),
|
||||
jsx: require('./grunt/config/jsx'),
|
||||
jsx: require('./grunt/config/jsx/jsx'),
|
||||
browserify: require('./grunt/config/browserify'),
|
||||
wrapup: require('./grunt/config/wrapup'),
|
||||
populist: require('./grunt/config/populist'),
|
||||
connect: require('./grunt/config/server')(grunt),
|
||||
"webdriver-jasmine": require('./grunt/config/webdriver-jasmine'),
|
||||
"webdriver-perf": require('./grunt/config/webdriver-perf'),
|
||||
phantom: require('./grunt/config/phantom'),
|
||||
npm: require('./grunt/config/npm'),
|
||||
clean: ['./build', './*.gem', './docs/_site', './examples/shared/*.js', '.module-cache'],
|
||||
clean: ['./build', './*.gem', './docs/_site', './examples/shared/*.js'],
|
||||
jshint: require('./grunt/config/jshint'),
|
||||
compare_size: require('./grunt/config/compare_size'),
|
||||
complexity: require('./grunt/config/complexity')
|
||||
compare_size: require('./grunt/config/compare_size')
|
||||
});
|
||||
|
||||
grunt.config.set('compress', require('./grunt/config/compress'));
|
||||
|
||||
Object.keys(grunt.file.readJSON('package.json').devDependencies)
|
||||
.filter(function(npmTaskName) { return npmTaskName.indexOf('grunt-') === 0; })
|
||||
.filter(function(npmTaskName) { return npmTaskName != 'grunt-cli'; })
|
||||
.forEach(function(npmTaskName) { grunt.loadNpmTasks(npmTaskName); });
|
||||
grunt.loadNpmTasks('grunt-contrib-jshint');
|
||||
grunt.loadNpmTasks('grunt-contrib-copy');
|
||||
grunt.loadNpmTasks('grunt-contrib-clean');
|
||||
grunt.loadNpmTasks('grunt-compare-size');
|
||||
grunt.loadNpmTasks('grunt-contrib-compress');
|
||||
|
||||
// Alias 'jshint' to 'lint' to better match the workflow we know
|
||||
grunt.registerTask('lint', ['jshint']);
|
||||
|
||||
grunt.registerTask('download-previous-version', require('./grunt/tasks/download-previous-version.js'));
|
||||
|
||||
grunt.registerTask('delete-build-modules', function() {
|
||||
if (grunt.file.exists('build/modules')) {
|
||||
grunt.file.delete('build/modules');
|
||||
}
|
||||
});
|
||||
|
||||
// Register jsx:normal and :release tasks.
|
||||
// Register jsx:debug and :release tasks.
|
||||
grunt.registerMultiTask('jsx', jsxTask);
|
||||
|
||||
// Our own browserify-based tasks to build a single JS file build
|
||||
grunt.registerMultiTask('browserify', browserifyTask);
|
||||
|
||||
// Similar to Browserify, use WrapUp to generate single JS file that
|
||||
// defines global variables instead of using require.
|
||||
grunt.registerMultiTask('wrapup', wrapupTask);
|
||||
|
||||
grunt.registerMultiTask('populist', populistTask);
|
||||
|
||||
grunt.registerTask('sauce-tunnel', sauceTunnelTask);
|
||||
|
||||
grunt.registerMultiTask('webdriver-jasmine', webdriverJasmineTasks);
|
||||
|
||||
grunt.registerMultiTask('webdriver-perf', require('./grunt/tasks/webdriver-perf'));
|
||||
grunt.registerMultiTask('phantom', phantomTask);
|
||||
|
||||
grunt.registerMultiTask('npm', npmTask);
|
||||
|
||||
grunt.registerTask('npm-react:release', npmReactTasks.buildRelease);
|
||||
grunt.registerTask('npm-react:pack', npmReactTasks.packRelease);
|
||||
grunt.registerTask('npm-react-tools:pack', npmReactToolsTasks.pack);
|
||||
// Check that the version we're exporting is the same one we expect in the
|
||||
// package. This is not an ideal way to do this, but makes sure that we keep
|
||||
// them in sync.
|
||||
var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;
|
||||
grunt.registerTask('version-check', function() {
|
||||
var version = reactVersionExp.exec(
|
||||
grunt.file.read('./build/modules/React.js')
|
||||
)[1];
|
||||
var expectedVersion = grunt.config.data.pkg.version;
|
||||
if (version !== expectedVersion) {
|
||||
grunt.log.error('Versions do not match. Expected %s, saw %s', expectedVersion, version);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
grunt.registerTask('version-check', versionCheckTask);
|
||||
|
||||
grunt.registerTask('build:basic', ['jsx:normal', 'version-check', 'browserify:basic']);
|
||||
grunt.registerTask('build:addons', ['jsx:normal', 'browserify:addons']);
|
||||
grunt.registerTask('build:transformer', ['jsx:normal', 'browserify:transformer']);
|
||||
grunt.registerTask('build:min', ['jsx:normal', 'version-check', 'browserify:min']);
|
||||
grunt.registerTask('build:addons-min', ['jsx:normal', 'browserify:addonsMin']);
|
||||
grunt.registerTask('build:withCodeCoverageLogging', [
|
||||
'jsx:normal',
|
||||
'version-check',
|
||||
'browserify:withCodeCoverageLogging'
|
||||
]);
|
||||
grunt.registerTask('build:perf', [
|
||||
'jsx:normal',
|
||||
'version-check',
|
||||
'browserify:transformer',
|
||||
'browserify:basic',
|
||||
'browserify:min',
|
||||
'download-previous-version'
|
||||
]);
|
||||
grunt.registerTask('build:basic', ['jsx:debug', 'version-check', 'browserify:basic']);
|
||||
grunt.registerTask('build:addons', ['jsx:debug', 'browserify:addons']);
|
||||
grunt.registerTask('build:transformer', ['jsx:debug', 'browserify:transformer']);
|
||||
grunt.registerTask('build:min', ['jsx:release', 'version-check', 'browserify:min']);
|
||||
grunt.registerTask('build:addons-min', ['jsx:debug', 'browserify:addonsMin']);
|
||||
grunt.registerTask('build:test', [
|
||||
'delete-build-modules',
|
||||
'jsx:jasmine',
|
||||
'jsx:test',
|
||||
'version-check',
|
||||
'populist:jasmine',
|
||||
'populist:test'
|
||||
]);
|
||||
grunt.registerTask('build:npm-react', ['version-check', 'jsx:normal', 'npm-react:release']);
|
||||
|
||||
grunt.registerTask('webdriver-phantomjs', webdriverPhantomJSTask);
|
||||
|
||||
grunt.registerTask('coverage:parse', require('./grunt/tasks/coverage-parse'));
|
||||
|
||||
grunt.registerTask('test:webdriver:phantomjs', [
|
||||
'connect',
|
||||
'webdriver-phantomjs',
|
||||
'webdriver-jasmine:local'
|
||||
]);
|
||||
|
||||
grunt.registerTask('perf:webdriver:phantomjs', [
|
||||
'connect',
|
||||
'webdriver-phantomjs',
|
||||
'webdriver-perf:local'
|
||||
]);
|
||||
|
||||
grunt.registerTask('test:full', [
|
||||
'build:test',
|
||||
'build:basic',
|
||||
|
||||
'connect',
|
||||
'webdriver-phantomjs',
|
||||
'webdriver-jasmine:local',
|
||||
|
||||
'sauce-tunnel',
|
||||
'webdriver-jasmine:saucelabs_android',
|
||||
'webdriver-jasmine:saucelabs_firefox',
|
||||
'webdriver-jasmine:saucelabs_chrome'
|
||||
]);
|
||||
|
||||
grunt.registerTask('perf:full', [
|
||||
'build:perf',
|
||||
|
||||
'connect',
|
||||
'webdriver-phantomjs',
|
||||
'webdriver-perf:local',
|
||||
|
||||
'sauce-tunnel',
|
||||
'webdriver-perf:saucelabs_firefox',
|
||||
'webdriver-perf:saucelabs_chrome',
|
||||
'webdriver-perf:saucelabs_ie11',
|
||||
'webdriver-perf:saucelabs_ie8',
|
||||
]);
|
||||
|
||||
grunt.registerTask('test:webdriver:saucelabs', [
|
||||
'build:test',
|
||||
'build:basic',
|
||||
|
||||
'connect',
|
||||
'sauce-tunnel',
|
||||
'webdriver-jasmine:saucelabs_' + (process.env.BROWSER_NAME || 'ie8')
|
||||
]);
|
||||
|
||||
grunt.registerTask('test:webdriver:saucelabs:ie', [
|
||||
'build:test',
|
||||
'build:basic',
|
||||
|
||||
'connect',
|
||||
'sauce-tunnel',
|
||||
'webdriver-jasmine:saucelabs_ie8',
|
||||
'webdriver-jasmine:saucelabs_ie9',
|
||||
'webdriver-jasmine:saucelabs_ie10',
|
||||
'webdriver-jasmine:saucelabs_ie11'
|
||||
]);
|
||||
|
||||
grunt.registerTask('test:webdriver:saucelabs:ios', [
|
||||
'build:test',
|
||||
'build:basic',
|
||||
|
||||
'connect',
|
||||
'sauce-tunnel',
|
||||
'webdriver-jasmine:saucelabs_ios6_1',
|
||||
'webdriver-jasmine:saucelabs_ios5_1',
|
||||
'webdriver-jasmine:saucelabs_ios4'
|
||||
]);
|
||||
|
||||
grunt.registerTask('test:coverage', [
|
||||
'build:test',
|
||||
'build:withCodeCoverageLogging',
|
||||
'test:webdriver:phantomjs',
|
||||
'coverage:parse'
|
||||
]);
|
||||
grunt.registerTask('test', ['build:test', 'build:basic', 'test:webdriver:phantomjs']);
|
||||
grunt.registerTask('perf', ['build:perf', 'perf:webdriver:phantomjs']);
|
||||
grunt.registerTask('test', ['build:test', 'build:basic', 'phantom:run']);
|
||||
grunt.registerTask('npm:test', ['build', 'npm:pack']);
|
||||
|
||||
// Optimized build task that does all of our builds. The subtasks will be run
|
||||
// in order so we can take advantage of that and only run jsx:normal once.
|
||||
// in order so we can take advantage of that and only run jsx:debug once.
|
||||
grunt.registerTask('build', [
|
||||
'delete-build-modules',
|
||||
'jsx:normal',
|
||||
'jsx:debug',
|
||||
'version-check',
|
||||
'browserify:basic',
|
||||
'browserify:transformer',
|
||||
'browserify:addons',
|
||||
'jsx:release',
|
||||
'browserify:min',
|
||||
'browserify:addonsMin',
|
||||
'npm-react:release',
|
||||
'npm-react:pack',
|
||||
'npm-react-tools:pack',
|
||||
'copy:react_docs',
|
||||
'compare_size'
|
||||
]);
|
||||
|
||||
12
README.md
@@ -8,10 +8,6 @@ React is a JavaScript library for building user interfaces.
|
||||
|
||||
[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/autoflow) project, it's now in `npm` as `autoflow` 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:
|
||||
@@ -32,7 +28,7 @@ React.renderComponent(
|
||||
|
||||
This example will render "Hello John" into a container on the page.
|
||||
|
||||
You'll notice that we used an HTML-like syntax; [we call it JSX](http://facebook.github.io/react/docs/jsx-in-depth.html). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. A simple transform is included with React that allows converting JSX into native JavaScript for browsers to digest.
|
||||
You'll notice that we used an XML-like syntax; [we call it JSX](http://facebook.github.io/react/docs/jsx-in-depth.html). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. A simple transform is included with React that allows converting JSX into native JavaScript for browsers to digest.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -40,12 +36,12 @@ The fastest way to get started is to serve JavaScript from the CDN (also availab
|
||||
|
||||
```html
|
||||
<!-- The core React library -->
|
||||
<script src="http://fb.me/react-0.8.0.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.8.0.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.8.0.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
|
||||
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:
|
||||
|
||||
|
||||
20
bin/jsx
@@ -1,24 +1,12 @@
|
||||
#!/usr/bin/env node
|
||||
// -*- mode: js -*-
|
||||
"use strict";
|
||||
|
||||
var visitors = require('../vendor/fbtransform/visitors');
|
||||
var visitors = require('../vendor/fbtransform/visitors').transformVisitors;
|
||||
var transform = require('jstransform').transform;
|
||||
|
||||
require('commoner').version(
|
||||
require('../package.json').version
|
||||
).resolve(function(id) {
|
||||
require("commoner").resolve(function(id) {
|
||||
return this.readModuleP(id);
|
||||
}).option(
|
||||
'--harmony',
|
||||
'Turns on JS transformations such as ES6 Classes etc.'
|
||||
).process(function(id, source) {
|
||||
}).process(function(id, source) {
|
||||
// This is where JSX, ES6, etc. desugaring happens.
|
||||
var visitorList;
|
||||
if (this.options.harmony) {
|
||||
visitorList = visitors.getAllVisitors();
|
||||
} else {
|
||||
visitorList = visitors.transformVisitors.react;
|
||||
}
|
||||
return transform(visitorList, source).code;
|
||||
return transform(visitors.react, source).code;
|
||||
});
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
#!/usr/bin/env node
|
||||
// -*- mode: js -*-
|
||||
"use strict";
|
||||
|
||||
var getAllVisitors = require('../vendor/fbtransform/visitors').getAllVisitors;
|
||||
var visitors = require('../vendor/fbtransform/visitors').transformVisitors;
|
||||
var transform = require('jstransform').transform;
|
||||
var propagate = require("../vendor/constants").propagate;
|
||||
|
||||
require("commoner").version(
|
||||
require("../package.json").version
|
||||
).resolve(function(id) {
|
||||
require("commoner").resolve(function(id) {
|
||||
var context = this;
|
||||
|
||||
// Note that the result of context.getProvidedP() is cached for the
|
||||
@@ -31,7 +28,7 @@ require("commoner").version(
|
||||
var constants = context.config.constants || {};
|
||||
|
||||
// This is where JSX, ES6, etc. desugaring happens.
|
||||
source = transform(getAllVisitors(), source).code;
|
||||
source = transform(visitors.react, source).code;
|
||||
|
||||
// Constant propagation means removing any obviously dead code after
|
||||
// replacing constant expressions with literal (boolean) values.
|
||||
|
||||
@@ -13,9 +13,8 @@ redcarpet:
|
||||
pygments: true
|
||||
name: React
|
||||
markdown: redcarpet
|
||||
react_version: 0.9.0
|
||||
react_version: 0.5.2
|
||||
description: A JavaScript library for building user interfaces
|
||||
relative_permalinks: true
|
||||
paginate: 5
|
||||
paginate_path: /blog/page:num/
|
||||
timezone: America/Los_Angeles
|
||||
|
||||
@@ -290,7 +290,7 @@ h1, h2, h3, h4, h5, h6 {
|
||||
|
||||
.marketing-col {
|
||||
float: left;
|
||||
margin-left: 40px;
|
||||
margin-right: 40px;
|
||||
width: $columnWidth;
|
||||
|
||||
h3 {
|
||||
@@ -304,8 +304,8 @@ h1, h2, h3, h4, h5, h6 {
|
||||
}
|
||||
}
|
||||
|
||||
.marketing-col:first-child {
|
||||
margin-left: 0;
|
||||
.marketing-col:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
#examples h3, .home-presentation h3 {
|
||||
@@ -419,7 +419,7 @@ section.black content {
|
||||
|
||||
padding-top: 20px;
|
||||
|
||||
// Make a notice box out of blockquotes in the documentation:
|
||||
// Make a notice box out of blockquotes in the documetation:
|
||||
blockquote {
|
||||
padding: 15px 30px 15px 15px;
|
||||
margin: 20px 0;
|
||||
@@ -428,7 +428,7 @@ section.black content {
|
||||
h4 {
|
||||
margin-top: 0;
|
||||
}
|
||||
p {
|
||||
p:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
// Treat first child as the title - promote to H4.
|
||||
@@ -466,12 +466,6 @@ section.black content {
|
||||
@include code-typography;
|
||||
}
|
||||
}
|
||||
|
||||
.playgroundError {
|
||||
// The compiler view kills padding in order to render the CodeMirror code
|
||||
// more nicely. For the error view, put a padding back
|
||||
padding: 15px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Button */
|
||||
@@ -566,7 +560,7 @@ figure {
|
||||
margin-top: 60px;
|
||||
}
|
||||
|
||||
/* CodeMirror */
|
||||
/* Code Mirror */
|
||||
|
||||
div.CodeMirror pre, div.CodeMirror-linenumber, code {
|
||||
@include code-typography;
|
||||
@@ -580,11 +574,6 @@ div.CodeMirror-linenumber:after {
|
||||
border: none;
|
||||
}
|
||||
|
||||
/* hide the cursor. Mostly used when code's in plain JS */
|
||||
.CodeMirror-readonly div.CodeMirror-cursor {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
small code,
|
||||
li code,
|
||||
p code {
|
||||
@@ -601,28 +590,23 @@ p code {
|
||||
@include clearfix;
|
||||
}
|
||||
|
||||
.playground-tab {
|
||||
.playground::before {
|
||||
border-bottom: none !important;
|
||||
border-radius: 3px 3px 0 0;
|
||||
padding: 6px 8px;
|
||||
padding: 3px 7px;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
color: #c2c0bc;
|
||||
background-color: #f1ede4;
|
||||
display: inline-block;
|
||||
cursor: pointer;
|
||||
content: 'Live editor';
|
||||
}
|
||||
|
||||
.playground::before,
|
||||
.playgroundCode,
|
||||
.playground-tab,
|
||||
.playgroundPreview {
|
||||
border: 1px solid rgba(16,16,16,0.1);
|
||||
}
|
||||
|
||||
.playground-tab-active {
|
||||
color: $darkestColor;
|
||||
}
|
||||
|
||||
.playgroundCode {
|
||||
border-radius: 0 3px 3px 3px;
|
||||
float: left;
|
||||
@@ -638,11 +622,6 @@ p code {
|
||||
width: $columnWidth;
|
||||
}
|
||||
|
||||
.playgroundError {
|
||||
color: darken($primary, 5%);
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.MarkdownEditor textarea {
|
||||
width: 100%;
|
||||
height: 100px
|
||||
@@ -657,7 +636,7 @@ p code {
|
||||
padding-left: 9px;
|
||||
}
|
||||
|
||||
/* CodeMirror doesn't support <jsx> syntax. Instead of highlighting it
|
||||
/* Codemirror doesn't support <jsx> syntax. Instead of highlighting it
|
||||
as error, just ignore it */
|
||||
.highlight .javascript .err {
|
||||
background-color: transparent;
|
||||
@@ -744,8 +723,3 @@ p code {
|
||||
float: right;
|
||||
}
|
||||
}
|
||||
|
||||
// Twitter embeds. Need to !important because they inline margin on the iframe.
|
||||
div[data-twttr-id] iframe {
|
||||
margin: 10px auto !important;
|
||||
}
|
||||
|
||||
@@ -4,12 +4,6 @@
|
||||
title: Getting Started
|
||||
- id: tutorial
|
||||
title: Tutorial
|
||||
- id: videos
|
||||
title: Videos
|
||||
- id: complementary-tools
|
||||
title: Complementary Tools
|
||||
- id: example-apps
|
||||
title: Example Apps
|
||||
- title: Guides
|
||||
items:
|
||||
- id: why-react
|
||||
@@ -45,10 +39,6 @@
|
||||
title: Two-Way Binding Helpers
|
||||
- id: class-name-manipulation
|
||||
title: Class Name Manipulation
|
||||
- id: test-utils
|
||||
title: Test Utilities
|
||||
- id: clone-with-props
|
||||
title: Cloning Components
|
||||
- id: examples
|
||||
title: Examples
|
||||
- title: Reference
|
||||
@@ -65,7 +55,3 @@
|
||||
title: Event System
|
||||
- id: dom-differences
|
||||
title: DOM Differences
|
||||
- id: special-non-dom-attributes
|
||||
title: Special Non-DOM Attributes
|
||||
- id: reconciliation
|
||||
title: Reconciliation
|
||||
|
||||
@@ -28,5 +28,3 @@
|
||||
title: False in JSX
|
||||
- id: communicate-between-components
|
||||
title: Communicate Between Components
|
||||
- id: expose-component-functions
|
||||
title: Expose Component Functions
|
||||
|
||||
2
docs/_js/es5-sham.min.js
vendored
2
docs/_js/es5-shim.min.js
vendored
@@ -6,7 +6,7 @@ var HELLO_COMPONENT = "\
|
||||
/** @jsx React.DOM */\n\
|
||||
var HelloMessage = React.createClass({\n\
|
||||
render: function() {\n\
|
||||
return <div>Hello {this.props.name}</div>;\n\
|
||||
return <div>{'Hello ' + this.props.name}</div>;\n\
|
||||
}\n\
|
||||
});\n\
|
||||
\n\
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
*/
|
||||
|
||||
var TIMER_COMPONENT = "\
|
||||
/** @jsx React.DOM */\n\
|
||||
var Timer = React.createClass({\n\
|
||||
getInitialState: function() {\n\
|
||||
return {secondsElapsed: 0};\n\
|
||||
@@ -18,13 +17,13 @@ var Timer = React.createClass({\n\
|
||||
clearInterval(this.interval);\n\
|
||||
},\n\
|
||||
render: function() {\n\
|
||||
return (\n\
|
||||
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>\n\
|
||||
return React.DOM.div({},\n\
|
||||
'Seconds Elapsed: ', this.state.secondsElapsed\n\
|
||||
);\n\
|
||||
}\n\
|
||||
});\n\
|
||||
\n\
|
||||
React.renderComponent(<Timer />, mountNode);\
|
||||
React.renderComponent(Timer({}), mountNode);\
|
||||
";
|
||||
|
||||
React.renderComponent(
|
||||
|
||||
@@ -1,482 +0,0 @@
|
||||
/**
|
||||
* Copyright 2013-2014 Facebook, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is a very simple HTML to JSX converter. It turns out that browsers
|
||||
* have good HTML parsers (who would have thought?) so we utilise this by
|
||||
* inserting the HTML into a temporary DOM node, and then do a breadth-first
|
||||
* traversal of the resulting DOM tree.
|
||||
*/
|
||||
;(function(global) {
|
||||
'use strict';
|
||||
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType
|
||||
var NODE_TYPE = {
|
||||
ELEMENT: 1,
|
||||
TEXT: 3,
|
||||
COMMENT: 8
|
||||
};
|
||||
var ATTRIBUTE_MAPPING = {
|
||||
'for': 'htmlFor',
|
||||
'class': 'className'
|
||||
};
|
||||
|
||||
/**
|
||||
* Repeats a string a certain number of times.
|
||||
* Also: the future is bright and consists of native string repetition:
|
||||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
|
||||
*
|
||||
* @param {string} string String to repeat
|
||||
* @param {number} times Number of times to repeat string. Integer.
|
||||
* @see http://jsperf.com/string-repeater/2
|
||||
*/
|
||||
function repeatString(string, times) {
|
||||
if (times === 1) {
|
||||
return string;
|
||||
}
|
||||
if (times < 0) { throw new Error(); }
|
||||
var repeated = '';
|
||||
while (times) {
|
||||
if (times & 1) {
|
||||
repeated += string;
|
||||
}
|
||||
if (times >>= 1) {
|
||||
string += string;
|
||||
}
|
||||
}
|
||||
return repeated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the string ends with the specified substring.
|
||||
*
|
||||
* @param {string} haystack String to search in
|
||||
* @param {string} needle String to search for
|
||||
* @return {boolean}
|
||||
*/
|
||||
function endsWith(haystack, needle) {
|
||||
return haystack.slice(-needle.length) === needle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim the specified substring off the string. If the string does not end
|
||||
* with the specified substring, this is a no-op.
|
||||
*
|
||||
* @param {string} haystack String to search in
|
||||
* @param {string} needle String to search for
|
||||
* @return {string}
|
||||
*/
|
||||
function trimEnd(haystack, needle) {
|
||||
return endsWith(haystack, needle)
|
||||
? haystack.slice(0, -needle.length)
|
||||
: haystack;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a hyphenated string to camelCase.
|
||||
*/
|
||||
function hyphenToCamelCase(string) {
|
||||
return string.replace(/-(.)/g, function(match, chr) {
|
||||
return chr.toUpperCase();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the specified string consists entirely of whitespace.
|
||||
*/
|
||||
function isEmpty(string) {
|
||||
return !/[^\s]/.test(string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the specified string consists entirely of numeric characters.
|
||||
*/
|
||||
function isNumeric(input) {
|
||||
return input !== undefined
|
||||
&& input !== null
|
||||
&& (typeof input === 'number' || parseInt(input, 10) == input);
|
||||
}
|
||||
|
||||
var HTMLtoJSX = function(config) {
|
||||
this.config = config || {};
|
||||
|
||||
if (this.config.createClass === undefined) {
|
||||
this.config.createClass = true;
|
||||
}
|
||||
if (!this.config.indent) {
|
||||
this.config.indent = ' ';
|
||||
}
|
||||
if (!this.config.outputClassName) {
|
||||
this.config.outputClassName = 'NewComponent';
|
||||
}
|
||||
};
|
||||
HTMLtoJSX.prototype = {
|
||||
/**
|
||||
* Reset the internal state of the converter
|
||||
*/
|
||||
reset: function() {
|
||||
this.output = '';
|
||||
this.level = 0;
|
||||
},
|
||||
/**
|
||||
* Main entry point to the converter. Given the specified HTML, returns a
|
||||
* JSX object representing it.
|
||||
* @param {string} html HTML to convert
|
||||
* @return {string} JSX
|
||||
*/
|
||||
convert: function(html) {
|
||||
this.reset();
|
||||
|
||||
// It turns out browsers have good HTML parsers (imagine that).
|
||||
// Let's take advantage of it.
|
||||
var containerEl = document.createElement('div');
|
||||
containerEl.innerHTML = '\n' + this._cleanInput(html) + '\n';
|
||||
|
||||
if (this.config.createClass) {
|
||||
if (this.config.outputClassName) {
|
||||
this.output = 'var ' + this.config.outputClassName + ' = React.createClass({\n';
|
||||
} else {
|
||||
this.output = 'React.createClass({\n';
|
||||
}
|
||||
this.output += this.config.indent + 'render: function() {' + "\n";
|
||||
this.output += this.config.indent + this.config.indent + 'return (\n';
|
||||
}
|
||||
|
||||
if (this._onlyOneTopLevel(containerEl)) {
|
||||
// Only one top-level element, the component can return it directly
|
||||
// No need to actually visit the container element
|
||||
this._traverse(containerEl);
|
||||
} else {
|
||||
// More than one top-level element, need to wrap the whole thing in a
|
||||
// container.
|
||||
this.output += this.config.indent + this.config.indent + this.config.indent;
|
||||
this.level++;
|
||||
this._visit(containerEl);
|
||||
}
|
||||
this.output = this.output.trim() + '\n';
|
||||
if (this.config.createClass) {
|
||||
this.output += this.config.indent + this.config.indent + ');\n';
|
||||
this.output += this.config.indent + '}\n';
|
||||
this.output += '});';
|
||||
}
|
||||
return this.output;
|
||||
},
|
||||
|
||||
/**
|
||||
* Cleans up the specified HTML so it's in a format acceptable for
|
||||
* converting.
|
||||
*
|
||||
* @param {string} html HTML to clean
|
||||
* @return {string} Cleaned HTML
|
||||
*/
|
||||
_cleanInput: function(html) {
|
||||
// Remove unnecessary whitespace
|
||||
html = html.trim();
|
||||
// Ugly method to strip script tags. They can wreak havoc on the DOM nodes
|
||||
// so let's not even put them in the DOM.
|
||||
html = html.replace(/<script(.*?)<\/script>/g, '');
|
||||
return html;
|
||||
},
|
||||
|
||||
/**
|
||||
* Determines if there's only one top-level node in the DOM tree. That is,
|
||||
* all the HTML is wrapped by a single HTML tag.
|
||||
*
|
||||
* @param {DOMElement} containerEl Container element
|
||||
* @return {boolean}
|
||||
*/
|
||||
_onlyOneTopLevel: function(containerEl) {
|
||||
// Only a single child element
|
||||
if (
|
||||
containerEl.childNodes.length === 1
|
||||
&& containerEl.childNodes[0].nodeType === NODE_TYPE.ELEMENT
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
// Only one element, and all other children are whitespace
|
||||
var foundElement = false;
|
||||
for (var i = 0, count = containerEl.childNodes.length; i < count; i++) {
|
||||
var child = containerEl.childNodes[i];
|
||||
if (child.nodeType === NODE_TYPE.ELEMENT) {
|
||||
if (foundElement) {
|
||||
// Encountered an element after already encountering another one
|
||||
// Therefore, more than one element at root level
|
||||
return false;
|
||||
} else {
|
||||
foundElement = true;
|
||||
}
|
||||
} else if (child.nodeType === NODE_TYPE.TEXT && !isEmpty(child.textContent)) {
|
||||
// Contains text content
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets a newline followed by the correct indentation for the current
|
||||
* nesting level
|
||||
*
|
||||
* @return {string}
|
||||
*/
|
||||
_getIndentedNewline: function() {
|
||||
return '\n' + repeatString(this.config.indent, this.level + 2);
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles processing the specified node
|
||||
*
|
||||
* @param {Node} node
|
||||
*/
|
||||
_visit: function(node) {
|
||||
this._beginVisit(node);
|
||||
this._traverse(node);
|
||||
this._endVisit(node);
|
||||
},
|
||||
|
||||
/**
|
||||
* Traverses all the children of the specified node
|
||||
*
|
||||
* @param {Node} node
|
||||
*/
|
||||
_traverse: function(node) {
|
||||
this.level++;
|
||||
for (var i = 0, count = node.childNodes.length; i < count; i++) {
|
||||
this._visit(node.childNodes[i]);
|
||||
}
|
||||
this.level--;
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle pre-visit behaviour for the specified node.
|
||||
*
|
||||
* @param {Node} node
|
||||
*/
|
||||
_beginVisit: function(node) {
|
||||
switch (node.nodeType) {
|
||||
case NODE_TYPE.ELEMENT:
|
||||
this._beginVisitElement(node);
|
||||
break;
|
||||
|
||||
case NODE_TYPE.TEXT:
|
||||
this._visitText(node);
|
||||
break;
|
||||
|
||||
case NODE_TYPE.COMMENT:
|
||||
this._visitComment(node);
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn('Unrecognised node type: ' + node.nodeType);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles post-visit behaviour for the specified node.
|
||||
*
|
||||
* @param {Node} node
|
||||
*/
|
||||
_endVisit: function(node) {
|
||||
switch (node.nodeType) {
|
||||
case NODE_TYPE.ELEMENT:
|
||||
this._endVisitElement(node);
|
||||
break;
|
||||
// No ending tags required for these types
|
||||
case NODE_TYPE.TEXT:
|
||||
case NODE_TYPE.COMMENT:
|
||||
break;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles pre-visit behaviour for the specified element node
|
||||
*
|
||||
* @param {DOMElement} node
|
||||
*/
|
||||
_beginVisitElement: function(node) {
|
||||
var tagName = node.tagName.toLowerCase();
|
||||
var attributes = [];
|
||||
for (var i = 0, count = node.attributes.length; i < count; i++) {
|
||||
attributes.push(this._getElementAttribute(node, node.attributes[i]));
|
||||
}
|
||||
|
||||
this.output += '<' + tagName;
|
||||
if (attributes.length > 0) {
|
||||
this.output += ' ' + attributes.join(' ');
|
||||
}
|
||||
if (node.firstChild) {
|
||||
this.output += '>';
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles post-visit behaviour for the specified element node
|
||||
*
|
||||
* @param {Node} node
|
||||
*/
|
||||
_endVisitElement: function(node) {
|
||||
// De-indent a bit
|
||||
// TODO: It's inefficient to do it this way :/
|
||||
this.output = trimEnd(this.output, this.config.indent);
|
||||
if (node.firstChild) {
|
||||
this.output += '</' + node.tagName.toLowerCase() + '>';
|
||||
} else {
|
||||
this.output += ' />';
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles processing of the specified text node
|
||||
*
|
||||
* @param {TextNode} node
|
||||
*/
|
||||
_visitText: function(node) {
|
||||
var text = node.textContent;
|
||||
// If there's a newline in the text, adjust the indent level
|
||||
if (text.indexOf('\n') > -1) {
|
||||
text = node.textContent.replace(/\n\s*/g, this._getIndentedNewline());
|
||||
}
|
||||
this.output += text;
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles processing of the specified text node
|
||||
*
|
||||
* @param {Text} node
|
||||
*/
|
||||
_visitComment: function(node) {
|
||||
// Do not render the comment
|
||||
// Since we remove comments, we also need to remove the next line break so we
|
||||
// don't end up with extra whitespace after every comment
|
||||
//if (node.nextSibling && node.nextSibling.nodeType === NODE_TYPE.TEXT) {
|
||||
// node.nextSibling.textContent = node.nextSibling.textContent.replace(/\n\s*/, '');
|
||||
//}
|
||||
this.output += '{/*' + node.textContent.replace('*/', '* /') + '*/}';
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets a JSX formatted version of the specified attribute from the node
|
||||
*
|
||||
* @param {DOMElement} node
|
||||
* @param {object} attribute
|
||||
* @return {string}
|
||||
*/
|
||||
_getElementAttribute: function(node, attribute) {
|
||||
switch (attribute.name) {
|
||||
case 'style':
|
||||
return this._getStyleAttribute(attribute.value);
|
||||
default:
|
||||
var name = ATTRIBUTE_MAPPING[attribute.name] || attribute.name;
|
||||
var result = name + '=';
|
||||
// Numeric values should be output as {123} not "123"
|
||||
if (isNumeric(attribute.value)) {
|
||||
result += '{' + attribute.value + '}';
|
||||
} else {
|
||||
result += '"' + attribute.value.replace('"', '"') + '"';
|
||||
}
|
||||
return result;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets a JSX formatted version of the specified element styles
|
||||
*
|
||||
* @param {string} styles
|
||||
* @return {string}
|
||||
*/
|
||||
_getStyleAttribute: function(styles) {
|
||||
var jsxStyles = new StyleParser(styles).toJSXString();
|
||||
return 'style={{' + jsxStyles + '}}';
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles parsing of inline styles
|
||||
*
|
||||
* @param {string} rawStyle Raw style attribute
|
||||
* @constructor
|
||||
*/
|
||||
var StyleParser = function(rawStyle) {
|
||||
this.parse(rawStyle);
|
||||
};
|
||||
StyleParser.prototype = {
|
||||
/**
|
||||
* Parse the specified inline style attribute value
|
||||
* @param {string} rawStyle Raw style attribute
|
||||
*/
|
||||
parse: function(rawStyle) {
|
||||
this.styles = {};
|
||||
rawStyle.split(';').forEach(function(style) {
|
||||
style = style.trim();
|
||||
var firstColon = style.indexOf(':');
|
||||
var key = style.substr(0, firstColon);
|
||||
var value = style.substr(firstColon + 1).trim();
|
||||
if (key !== '') {
|
||||
this.styles[key] = value;
|
||||
}
|
||||
}, this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert the style information represented by this parser into a JSX
|
||||
* string
|
||||
*
|
||||
* @return {string}
|
||||
*/
|
||||
toJSXString: function() {
|
||||
var output = [];
|
||||
for (var key in this.styles) {
|
||||
if (!this.styles.hasOwnProperty(key)) {
|
||||
continue;
|
||||
}
|
||||
output.push(this.toJSXKey(key) + ': ' + this.toJSXValue(this.styles[key]));
|
||||
}
|
||||
return output.join(', ');
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert the CSS style key to a JSX style key
|
||||
*
|
||||
* @param {string} key CSS style key
|
||||
* @return {string} JSX style key
|
||||
*/
|
||||
toJSXKey: function(key) {
|
||||
return hyphenToCamelCase(key);
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert the CSS style value to a JSX style value
|
||||
*
|
||||
* @param {string} value CSS style value
|
||||
* @return {string} JSX style value
|
||||
*/
|
||||
toJSXValue: function(value) {
|
||||
if (isNumeric(value)) {
|
||||
// If numeric, no quotes
|
||||
return value;
|
||||
} else if (endsWith(value, 'px')) {
|
||||
// "500px" -> 500
|
||||
return trimEnd(value, 'px');
|
||||
} else {
|
||||
// Proably a string, wrap it in quotes
|
||||
return '\'' + value.replace(/'/g, '"') + '\'';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Expose public API
|
||||
global.HTMLtoJSX = HTMLtoJSX;
|
||||
}(window));
|
||||
@@ -1,89 +0,0 @@
|
||||
/**
|
||||
* Copyright 2013-2014 Facebook, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* @jsx React.DOM
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is a web interface for the HTML to JSX converter contained in
|
||||
* `html-jsx-lib.js`.
|
||||
*/
|
||||
;(function() {
|
||||
|
||||
var HELLO_COMPONENT = "\
|
||||
<!-- Hello world -->\n\
|
||||
<div class=\"awesome\" style=\"border: 1px solid red\">\n\
|
||||
<label for=\"name\">Enter your name: </label>\n\
|
||||
<input type=\"text\" id=\"name\" />\n\
|
||||
</div>\n\
|
||||
<p>Enter your HTML here</p>\
|
||||
";
|
||||
|
||||
var HTMLtoJSXComponent = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {
|
||||
outputClassName: 'NewComponent',
|
||||
createClass: true
|
||||
};
|
||||
},
|
||||
onReactClassNameChange: function(evt) {
|
||||
this.setState({ outputClassName: evt.target.value });
|
||||
},
|
||||
onCreateClassChange: function(evt) {
|
||||
this.setState({ createClass: evt.target.checked });
|
||||
},
|
||||
setInput: function(input) {
|
||||
this.setState({ input: input });
|
||||
this.convertToJsx();
|
||||
},
|
||||
convertToJSX: function(input) {
|
||||
var converter = new HTMLtoJSX({
|
||||
outputClassName: this.state.outputClassName,
|
||||
createClass: this.state.createClass
|
||||
});
|
||||
return converter.convert(input);
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div>
|
||||
<div id="options">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={this.state.createClass}
|
||||
onChange={this.onCreateClassChange} />
|
||||
Create class
|
||||
</label>
|
||||
<label style={{display: this.state.createClass ? '' : 'none'}}>
|
||||
·
|
||||
Class name:
|
||||
<input
|
||||
type="text"
|
||||
value={this.state.outputClassName}
|
||||
onChange={this.onReactClassNameChange} />
|
||||
</label>
|
||||
</div>
|
||||
<ReactPlayground
|
||||
codeText={HELLO_COMPONENT}
|
||||
renderCode={true}
|
||||
transformer={this.convertToJSX}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<HTMLtoJSXComponent />, document.getElementById('jsxCompiler'));
|
||||
}());
|
||||
8
docs/_js/html5shiv.min.js
vendored
@@ -1,8 +0,0 @@
|
||||
/*
|
||||
HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
|
||||
*/
|
||||
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
|
||||
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>";
|
||||
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
|
||||
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment();
|
||||
for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
|
||||
@@ -6,22 +6,14 @@ var HELLO_COMPONENT = "\
|
||||
/** @jsx React.DOM */\n\
|
||||
var HelloMessage = React.createClass({\n\
|
||||
render: function() {\n\
|
||||
return <div>Hello {this.props.name}</div>;\n\
|
||||
return <div>{'Hello ' + this.props.name}</div>;\n\
|
||||
}\n\
|
||||
});\n\
|
||||
\n\
|
||||
React.renderComponent(<HelloMessage name=\"John\" />, mountNode);\
|
||||
";
|
||||
|
||||
var transformer = function(code) {
|
||||
return JSXTransformer.transform(code).code;
|
||||
}
|
||||
React.renderComponent(
|
||||
<ReactPlayground
|
||||
codeText={HELLO_COMPONENT}
|
||||
renderCode={true}
|
||||
transformer={transformer}
|
||||
showCompiledJSTab={false}
|
||||
/>,
|
||||
<ReactPlayground codeText={HELLO_COMPONENT} renderCode={true} />,
|
||||
document.getElementById('jsxCompiler')
|
||||
);
|
||||
|
||||
@@ -14,33 +14,26 @@ var IS_MOBILE = (
|
||||
);
|
||||
|
||||
var CodeMirrorEditor = React.createClass({
|
||||
componentDidMount: function() {
|
||||
if (IS_MOBILE) return;
|
||||
|
||||
componentDidMount: function(root) {
|
||||
if (IS_MOBILE) {
|
||||
return;
|
||||
}
|
||||
this.editor = CodeMirror.fromTextArea(this.refs.editor.getDOMNode(), {
|
||||
mode: 'javascript',
|
||||
lineNumbers: false,
|
||||
lineWrapping: true,
|
||||
smartIndent: false, // javascript mode does bad things with jsx indents
|
||||
matchBrackets: true,
|
||||
theme: 'solarized-light',
|
||||
readOnly: this.props.readOnly
|
||||
});
|
||||
this.editor.on('change', this.handleChange);
|
||||
this.editor.on('change', this.onChange);
|
||||
this.onChange();
|
||||
},
|
||||
|
||||
componentDidUpdate: function() {
|
||||
if (this.props.readOnly) {
|
||||
this.editor.setValue(this.props.codeText);
|
||||
onChange: function() {
|
||||
if (this.props.onChange) {
|
||||
var content = this.editor.getValue();
|
||||
this.props.onChange(content);
|
||||
}
|
||||
},
|
||||
|
||||
handleChange: function() {
|
||||
if (!this.props.readOnly) {
|
||||
this.props.onChange && this.props.onChange(this.editor.getValue());
|
||||
}
|
||||
},
|
||||
|
||||
render: function() {
|
||||
// wrap in a div to fully contain CodeMirror
|
||||
var editor;
|
||||
@@ -52,115 +45,52 @@ var CodeMirrorEditor = React.createClass({
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={this.props.style} className={this.props.className}>
|
||||
<div className={this.props.className}>
|
||||
{editor}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
var selfCleaningTimeout = {
|
||||
componentDidUpdate: function() {
|
||||
clearTimeout(this.timeoutID);
|
||||
},
|
||||
|
||||
setTimeout: function() {
|
||||
clearTimeout(this.timeoutID);
|
||||
this.timeoutID = setTimeout.apply(null, arguments);
|
||||
}
|
||||
};
|
||||
|
||||
var ReactPlayground = React.createClass({
|
||||
mixins: [selfCleaningTimeout],
|
||||
|
||||
MODES: {JSX: 'JSX', JS: 'JS'}, //keyMirror({JSX: true, JS: true}),
|
||||
|
||||
propTypes: {
|
||||
codeText: React.PropTypes.string.isRequired,
|
||||
transformer: React.PropTypes.func,
|
||||
renderCode: React.PropTypes.bool,
|
||||
},
|
||||
|
||||
getDefaultProps: function() {
|
||||
return {
|
||||
transformer: function(code) {
|
||||
return JSXTransformer.transform(code).code;
|
||||
},
|
||||
showCompiledJSTab: true
|
||||
};
|
||||
},
|
||||
MODES: {XJS: 'XJS', JS: 'JS'}, //keyMirror({XJS: true, JS: true}),
|
||||
|
||||
getInitialState: function() {
|
||||
return {
|
||||
mode: this.MODES.JSX,
|
||||
code: this.props.codeText,
|
||||
};
|
||||
return {mode: this.MODES.XJS, code: this.props.codeText};
|
||||
},
|
||||
|
||||
handleCodeChange: function(value) {
|
||||
this.setState({code: value});
|
||||
this.executeCode();
|
||||
bindState: function(name) {
|
||||
return function(value) {
|
||||
var newState = {};
|
||||
newState[name] = value;
|
||||
this.setState(newState);
|
||||
}.bind(this);
|
||||
},
|
||||
|
||||
handleCodeModeSwitch: function(mode) {
|
||||
this.setState({mode: mode});
|
||||
},
|
||||
|
||||
compileCode: function() {
|
||||
return this.props.transformer(this.state.code);
|
||||
getDesugaredCode: function() {
|
||||
return JSXTransformer.transform(this.state.code).code;
|
||||
},
|
||||
|
||||
render: function() {
|
||||
var isJS = this.state.mode === this.MODES.JS;
|
||||
var compiledCode = '';
|
||||
try {
|
||||
compiledCode = this.compileCode();
|
||||
} catch (err) {}
|
||||
|
||||
var JSContent =
|
||||
<CodeMirrorEditor
|
||||
key="js"
|
||||
className="playgroundStage CodeMirror-readonly"
|
||||
onChange={this.handleCodeChange}
|
||||
codeText={compiledCode}
|
||||
readOnly={true}
|
||||
/>;
|
||||
|
||||
var JSXContent =
|
||||
<CodeMirrorEditor
|
||||
key="jsx"
|
||||
onChange={this.handleCodeChange}
|
||||
className="playgroundStage"
|
||||
codeText={this.state.code}
|
||||
/>;
|
||||
|
||||
var JSXTabClassName =
|
||||
'playground-tab' + (isJS ? '' : ' playground-tab-active');
|
||||
var JSTabClassName =
|
||||
'playground-tab' + (isJS ? ' playground-tab-active' : '');
|
||||
|
||||
var JSTab =
|
||||
<div
|
||||
className={JSTabClassName}
|
||||
onClick={this.handleCodeModeSwitch.bind(this, this.MODES.JS)}>
|
||||
Compiled JS
|
||||
</div>;
|
||||
|
||||
var JSXTab =
|
||||
<div
|
||||
className={JSXTabClassName}
|
||||
onClick={this.handleCodeModeSwitch.bind(this, this.MODES.JSX)}>
|
||||
Live JSX Editor
|
||||
</div>
|
||||
var content;
|
||||
if (this.state.mode === this.MODES.XJS) {
|
||||
content =
|
||||
<CodeMirrorEditor
|
||||
onChange={this.bindState('code')}
|
||||
className="playgroundStage"
|
||||
codeText={this.state.code}
|
||||
/>;
|
||||
} else if (this.state.mode === this.MODES.JS) {
|
||||
content =
|
||||
<div className="playgroundJS playgroundStage">
|
||||
{this.getDesugaredCode()}
|
||||
</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="playground">
|
||||
<div>
|
||||
{JSXTab}
|
||||
{this.props.showCompiledJSTab && JSTab}
|
||||
</div>
|
||||
<div className="playgroundCode">
|
||||
{isJS ? JSContent : JSXContent}
|
||||
{content}
|
||||
</div>
|
||||
<div className="playgroundPreview">
|
||||
<div ref="mount" />
|
||||
@@ -168,43 +98,35 @@ var ReactPlayground = React.createClass({
|
||||
</div>
|
||||
);
|
||||
},
|
||||
|
||||
componentDidMount: function() {
|
||||
this.executeCode();
|
||||
},
|
||||
|
||||
componentWillUpdate: function(nextProps, nextState) {
|
||||
// execute code only when the state's not being updated by switching tab
|
||||
// this avoids re-displaying the error, which comes after a certain delay
|
||||
if (this.state.code !== nextState.code) {
|
||||
this.executeCode();
|
||||
}
|
||||
componentDidUpdate: function() {
|
||||
this.executeCode();
|
||||
},
|
||||
|
||||
executeCode: function() {
|
||||
var mountNode = this.refs.mount.getDOMNode();
|
||||
|
||||
try {
|
||||
React.unmountComponentAtNode(mountNode);
|
||||
React.unmountAndReleaseReactRootNode(mountNode);
|
||||
} catch (e) { }
|
||||
|
||||
try {
|
||||
var compiledCode = this.compileCode();
|
||||
var desugaredCode = this.getDesugaredCode();
|
||||
if (this.props.renderCode) {
|
||||
React.renderComponent(
|
||||
<CodeMirrorEditor codeText={compiledCode} readOnly={true} />,
|
||||
<CodeMirrorEditor codeText={desugaredCode} readOnly={true} />,
|
||||
mountNode
|
||||
);
|
||||
} else {
|
||||
eval(compiledCode);
|
||||
eval(desugaredCode);
|
||||
}
|
||||
} catch (err) {
|
||||
this.setTimeout(function() {
|
||||
React.renderComponent(
|
||||
<div className="playgroundError">{err.toString()}</div>,
|
||||
mountNode
|
||||
);
|
||||
}, 500);
|
||||
} catch (e) {
|
||||
React.renderComponent(
|
||||
<div content={e.toString()} className="playgroundError" />,
|
||||
mountNode
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!--[if IE]><![endif]-->
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
@@ -16,18 +15,13 @@
|
||||
<link rel="shortcut icon" href="/react/favicon.ico">
|
||||
<link rel="alternate" type="application/rss+xml" title="{{ site.name }}" href="{{ site.url }}{{ site.baseurl }}/feed.xml">
|
||||
|
||||
<link rel="stylesheet" href="/react/css/react.css">
|
||||
<link rel="stylesheet" href="/react/css/syntax.css">
|
||||
<link rel="stylesheet" href="/react/css/codemirror.css">
|
||||
<link rel="stylesheet" href="/react/css/react.css">
|
||||
|
||||
<script type="text/javascript" src="//use.typekit.net/vqa1hcx.js"></script>
|
||||
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
|
||||
|
||||
<!--[if lte IE 8]>
|
||||
<script type="text/javascript" src="/react/js/html5shiv.min.js"></script>
|
||||
<script type="text/javascript" src="/react/js/es5-shim.min.js"></script>
|
||||
<script type="text/javascript" src="/react/js/es5-sham.min.js"></script>
|
||||
<![endif]-->
|
||||
<script type="text/javascript" src="/react/js/codemirror.js"></script>
|
||||
<script type="text/javascript" src="/react/js/javascript.js"></script>
|
||||
<script type="text/javascript" src="/react/js/react.min.js"></script>
|
||||
@@ -46,12 +40,13 @@
|
||||
React
|
||||
</a>
|
||||
<ul class="nav-site">
|
||||
<li><a href="/react/docs/getting-started.html"{% if page.sectionid == 'docs' or page.sectionid == 'tips' %} class="active"{% endif %}>docs</a></li>
|
||||
<li><a href="/react/docs/getting-started.html"{% if page.sectionid == 'docs' %} class="active"{% endif %}>docs</a></li>
|
||||
<li><a href="/react/support.html"{% if page.id == 'support' %} class="active"{% endif %}>support</a></li>
|
||||
<li><a href="/react/downloads.html"{% if page.id == 'downloads' %} class="active"{% endif %}>download</a></li>
|
||||
<li><a href="/react/blog/"{% if page.sectionid == 'blog' %} class="active"{% endif %}>blog</a></li>
|
||||
<li><a href="http://github.com/facebook/react">github</a>
|
||||
</ul>
|
||||
<!-- <iframe src="http://ghbtns.com/github-btn.html?user=facebook&repo=react.js&type=fork"allowtransparency="true" frameborder="0" scrolling="0" width="62" height="20"></iframe> -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -75,7 +70,7 @@
|
||||
|
||||
<footer class="wrap">
|
||||
<div class="left">A Facebook & Instagram collaboration.</div>
|
||||
<div class="right">© 2014 Facebook Inc.</div>
|
||||
<div class="right">© 2013 Facebook Inc.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<div id="fb-root"></div>
|
||||
|
||||
@@ -31,8 +31,8 @@ to render views, which we see as an advantage over templates for a few reasons:
|
||||
**no manual string concatenation** and therefore less surface area for XSS
|
||||
vulnerabilities.
|
||||
|
||||
We've also created [JSX](/react/docs/jsx-in-depth.html), an optional syntax
|
||||
extension, in case you prefer the readability of HTML to raw JavaScript.
|
||||
We've also created [JSX](http://facebook.github.io/react/docs/syntax.html), an optional
|
||||
syntax extension, in case you prefer the readability of HTML to raw JavaScript.
|
||||
|
||||
## Reactive updates are dead simple.
|
||||
|
||||
@@ -41,7 +41,7 @@ React really shines when your data changes over time.
|
||||
In a traditional JavaScript application, you need to look at what data changed
|
||||
and imperatively make changes to the DOM to keep it up-to-date. Even AngularJS,
|
||||
which provides a declarative interface via directives and data binding [requires
|
||||
a linking function to manually update DOM nodes](http://code.angularjs.org/1.0.8/docs/guide/directive#reasonsbehindthecompilelinkseparation).
|
||||
a linking function to manually update DOM nodes](http://docs.angularjs.org/guide/directive#reasonsbehindthecompilelinkseparation).
|
||||
|
||||
React takes a different approach.
|
||||
|
||||
@@ -81,9 +81,11 @@ some pretty cool things with it:
|
||||
(including IE8) and automatically use
|
||||
[event delegation](http://davidwalsh.name/event-delegate).
|
||||
|
||||
Head on over to [facebook.github.io/react](/react) to check out what we have
|
||||
built. Our documentation is geared towards building apps with the framework,
|
||||
but if you are interested in the nuts and bolts
|
||||
[get in touch](/react/support.html) with us!
|
||||
Head on over to
|
||||
[facebook.github.io/react](http://facebook.github.io/react) to check
|
||||
out what we have built. Our documentation is geared towards building
|
||||
apps with the framework, but if you are interested in the
|
||||
nuts and bolts
|
||||
[get in touch](http://facebook.github.io/react/support.html) with us!
|
||||
|
||||
Thanks for reading!
|
||||
|
||||
@@ -59,7 +59,7 @@ Now that we've identified the components in our mock, let's arrange them into a
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/6wQMG/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
|
||||
Now that you have your component hierarchy it's time to start implementing your app. The easiest way is to build a version that takes your data model and renders the UI but has no interactivity. It's easiest to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing. We'll see why.
|
||||
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.
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
---
|
||||
title: "React v0.8"
|
||||
layout: post
|
||||
author: Paul O'Shannessy
|
||||
---
|
||||
|
||||
I'll start by answering the obvious question:
|
||||
|
||||
> What happened to 0.6 and 0.7?
|
||||
|
||||
It's become increasingly obvious since our launch in May that people want to use React on the server. With the server-side rendering abilities, that's a perfect fit. However using the same copy of React on the server and then packaging it up for the client is surprisingly a harder problem. People have been using our `react-tools` module which includes React, but when browserifying that ends up packaging all of `esprima` and some other dependencies that aren't needed on the client. So we wanted to make this whole experience better.
|
||||
|
||||
We talked with [Jeff Barczewski][jeff] who was the owner of the `react` module on npm. He was kind enough to transition ownership to us and release his package under a different name: `autoflow`. I encourage you to [check it out][autoflow] if you're writing a lot of asynchronous code. In order to not break all of `react`'s current users of 0.7.x, we decided to bump our version to 0.8 and skip the issue entirely. We're also including a warning if you use our `react` module like you would use the previous package.
|
||||
|
||||
In order to make the transition to 0.8 for our current users as painless as possible, we decided to make 0.8 primarily a bug fix release on top of 0.5. No public APIs were changed (even if they were already marked as deprecated). We haven't added any of the new features we have in master, though we did take the opportunity to pull in some improvements to internals.
|
||||
|
||||
We hope that by releasing `react` on npm, we will enable a new set of uses that have been otherwise difficult. All feedback is welcome!
|
||||
|
||||
|
||||
## Changelog
|
||||
|
||||
### React
|
||||
|
||||
* Added support for more attributes:
|
||||
* `rows` & `cols` for `<textarea>`
|
||||
* `defer` & `async` for `<script>`
|
||||
* `loop` for `<audio>` & `<video>`
|
||||
* `autoCorrect` for form fields (a non-standard attribute only supported by mobile WebKit)
|
||||
* Improved error messages
|
||||
* Fixed Selection events in IE11
|
||||
* Added `onContextMenu` events
|
||||
|
||||
### React with Addons
|
||||
|
||||
* Fixed bugs with TransitionGroup when children were undefined
|
||||
* Added support for `onTransition`
|
||||
|
||||
### react-tools
|
||||
|
||||
* Upgraded `jstransform` and `esprima-fb`
|
||||
|
||||
### JSXTransformer
|
||||
|
||||
* Added support for use in IE8
|
||||
* Upgraded browserify, which reduced file size by ~65KB (16KB gzipped)
|
||||
|
||||
[jeff]: https://github.com/jeffbski
|
||||
[autoflow]: https://github.com/jeffbski/autoflow
|
||||
@@ -1,105 +0,0 @@
|
||||
---
|
||||
title: "Community Round-up #12"
|
||||
layout: post
|
||||
author: Vjeux
|
||||
---
|
||||
|
||||
React got featured on the front-page of Hacker News thanks to the Om library. If you try it out for the first time, take a look at the [docs](/react/docs/getting-started.html) and do not hesitate to ask questions on the [Google Group](http://groups.google.com/group/reactjs), [IRC](irc://chat.freenode.net/reactjs) or [Stack Overflow](http://stackoverflow.com/questions/tagged/reactjs). We are trying our best to help you out!
|
||||
|
||||
## The Future of Javascript MVC
|
||||
|
||||
[David Nolen](http://swannodette.github.io/) announced Om, a thin wrapper on-top of React in ClojureScript. It stands out by only using immutable data structures. This unlocks the ability to write a very efficient [shouldComponentUpdate](http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate) and get huge performance improvements on some tasks.
|
||||
|
||||
> We've known this for some time over here in the ClojureScript corner of the world - all of our collections are immutable and modeled directly on the original Clojure versions written in Java. Modern JavaScript engines have now been tuned to the point that it's no longer uncommon to see collection performance within 2.5X of the Java Virtual Machine.
|
||||
>
|
||||
> Wait, wait, wait. What does the performance of persistent data structures have to do with the future of JavaScript MVCs?
|
||||
>
|
||||
> A whole lot.
|
||||
> <figure>[](http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/)</figure>
|
||||
>
|
||||
> [Read the full article...](http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/)
|
||||
|
||||
|
||||
|
||||
## Scroll Position with React
|
||||
|
||||
Managing the scroll position when new content is inserted is usually very tricky to get right. [Vjeux](http://blog.vjeux.com/) discovered that [componentWillUpdate](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate) and [componentDidUpdate](http://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate) were triggered exactly at the right time to manage the scroll position.
|
||||
|
||||
> We can check the scroll position before the component has updated with componentWillUpdate and scroll if necessary at componentDidUpdate
|
||||
>
|
||||
> ```
|
||||
componentWillUpdate: function() {
|
||||
var node = this.getDOMNode();
|
||||
this.shouldScrollBottom =
|
||||
(node.scrollTop + node.offsetHeight) === node.scrollHeight;
|
||||
},
|
||||
componentDidUpdate: function() {
|
||||
if (this.shouldScrollBottom) {
|
||||
var node = this.getDOMNode();
|
||||
node.scrollTop = node.scrollHeight
|
||||
}
|
||||
},
|
||||
```
|
||||
>
|
||||
> [Check out the blog article...](http://blog.vjeux.com/2013/javascript/scroll-position-with-react.html)
|
||||
|
||||
|
||||
## Lights Out
|
||||
|
||||
React declarative approach is well suited to write games. [Cheng Lou](https://github.com/chenglou) wrote the famous Lights Out game in React. It's a good example of use of [TransitionGroup](http://facebook.github.io/react/docs/animation.html) to implement animations.
|
||||
<figure>[](http://chenglou.github.io/react-lights-out/)</figure>
|
||||
|
||||
[Try it out!](http://chenglou.github.io/react-lights-out/)
|
||||
|
||||
|
||||
## Reactive Table Bookmarklet
|
||||
|
||||
[Stoyan Stefanov](http://www.phpied.com/) wrote a bookmarklet to process tables on the internet. It adds a little "pop" button that expands to a full-screen view with sorting, editing and export to csv and json.
|
||||
<figure>[](http://www.phpied.com/reactivetable-bookmarklet/)</figure>
|
||||
|
||||
[Check out the blog post...](http://www.phpied.com/reactivetable-bookmarklet/)
|
||||
|
||||
|
||||
## MontageJS Tutorial in React
|
||||
|
||||
[Ross Allen](https://twitter.com/ssorallen) implemented [MontageJS](http://montagejs.org/)'s [Reddit tutorial](http://montagejs.org/docs/tutorial-reddit-client-with-montagejs.html) in React. This is a good opportunity to compare the philosophies of the two libraries.
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/ssorallen/fEsYt/embedded/result,html,js" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
|
||||
[View the source on JSFiddle...](http://jsfiddle.net/ssorallen/fEsYt/)
|
||||
|
||||
## Writing Good React Components
|
||||
|
||||
[William Högman Rudenmalm](http://blog.whn.se/) wrote an article on how to write good React components. This is full of good advice.
|
||||
|
||||
> The idea of dividing software into smaller parts or components is hardly new - It is the essance of good software. The same principles that apply to software in general apply to building React components. That doesn’t mean that writing good React components is just about applying general rules.
|
||||
>
|
||||
> The web offers a unique set of challenges, which React offers interesting solutions to. First and foremost among these solutions is the what is called the Mock DOM. Rather than having user code interface with the DOM in a direct fashion, as is the case with most DOM manipulation libraries.
|
||||
>
|
||||
> You build a model of how you want the DOM end up like. React then inserts this model into the DOM. This is very useful for updates because React simply compares the model or mock DOM against the actual DOM, and then only updates based on the difference between the two states.
|
||||
>
|
||||
> [Read the full article ...](http://blog.whn.se/post/69621609605/writing-good-react-components)
|
||||
|
||||
|
||||
## Hoodie React TodoMVC
|
||||
|
||||
[Sven Lito](http://svenlito.com/) integrated the React TodoMVC example within an [Hoodie](http://hood.ie/) web app environment. This should let you get started using Hoodie and React.
|
||||
|
||||
```
|
||||
hoodie new todomvc -t "hoodiehq/hoodie-react-todomvc"
|
||||
```
|
||||
|
||||
[Check out on GitHub...](https://github.com/hoodiehq/hoodie-react-todomvc)
|
||||
|
||||
## JSX Compiler
|
||||
|
||||
Ever wanted to have a quick way to see what a JSX tag would be converted to? [Tim Yung](http://www.yungsters.com/) made a page for it.
|
||||
<figure>[](http://facebook.github.io/react/jsx-compiler.html)</figure>
|
||||
|
||||
[Try it out!](http://facebook.github.io/react/jsx-compiler.html)
|
||||
|
||||
|
||||
|
||||
## Random Tweet
|
||||
|
||||
<center><blockquote class="twitter-tweet" lang="en"><p>.<a href="https://twitter.com/jordwalke">@jordwalke</a> lays down some truth <a href="http://t.co/AXAn0UlUe3">http://t.co/AXAn0UlUe3</a>, optimizing your JS application shouldn't force you to rewrite so much code <a href="https://twitter.com/search?q=%23reactjs&src=hash">#reactjs</a></p>— David Nolen (@swannodette) <a href="https://twitter.com/swannodette/statuses/413780079249215488">December 19, 2013</a></blockquote></center>
|
||||
@@ -1,119 +0,0 @@
|
||||
---
|
||||
title: "Community Round-up #13"
|
||||
layout: post
|
||||
author: Vjeux
|
||||
---
|
||||
|
||||
Happy holidays! This blog post is a little-late Christmas present for all the React users. Hopefully it will inspire you to write awesome web apps in 2014!
|
||||
|
||||
|
||||
## React Touch
|
||||
|
||||
[Pete Hunt](http://www.petehunt.net/) wrote three demos showing that React can be used to run 60fps native-like experiences on mobile web. A frosted glass effect, an image gallery with 3d animations and an infinite scroll view.
|
||||
|
||||
<figure><iframe src="//player.vimeo.com/video/79659941" width="220" height="400" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></figure>
|
||||
|
||||
[Try out the demos!](http://petehunt.github.io/react-touch/)
|
||||
|
||||
|
||||
## Introduction to React
|
||||
|
||||
[Stoyan Stefanov](http://www.phpied.com/) talked at Joe Dev On Tech about React. He goes over all the features of the library and ends with a concrete example.
|
||||
|
||||
<figure><iframe width="560" height="315" src="//www.youtube.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe></figure>
|
||||
|
||||
|
||||
## JSX: E4X The Good Parts
|
||||
|
||||
JSX is often compared to the now defunct E4X, [Vjeux](http://blog.vjeux.com/) went over all the E4X features and explained how JSX is different and hopefully doesn't repeat the same mistakes.
|
||||
|
||||
> E4X (ECMAScript for XML) is a Javascript syntax extension and a runtime to manipulate XML. It was promoted by Mozilla but failed to become mainstream and is now deprecated. JSX was inspired by E4X. In this article, I'm going to go over all the features of E4X and explain the design decisions behind JSX.
|
||||
>
|
||||
> **Historical Context**
|
||||
>
|
||||
> E4X has been created in 2002 by John Schneider. This was the golden age of XML where it was being used for everything: data, configuration files, code, interfaces (DOM) ... E4X was first implemented inside of Rhino, a Javascript implementation from Mozilla written in Java.
|
||||
>
|
||||
> [Continue reading ...](http://blog.vjeux.com/2013/javascript/jsx-e4x-the-good-parts.html)
|
||||
|
||||
|
||||
## React + Socket.io
|
||||
|
||||
[Geert Pasteels](http://enome.be/nl) made a small experiment with Socket.io. He wrote a very small mixin that synchronizes React state with the server. Just include this mixin to your React component and it is now live!
|
||||
|
||||
```javascript
|
||||
changeHandler: function (data) {
|
||||
if (!_.isEqual(data.state, this.state) && this.path === data.path) {
|
||||
this.setState(data.state);
|
||||
}
|
||||
},
|
||||
componentDidMount: function (root) {
|
||||
this.path = utils.nodePath(root);
|
||||
socket.on('component-change', this.changeHandler);
|
||||
},
|
||||
componentWillUpdate: function (props, state) {
|
||||
socket.emit('component-change', { path: this.path, state: state });
|
||||
},
|
||||
componentWillUnmount: function () {
|
||||
socket.removeListener('component-change', this.change);
|
||||
}
|
||||
```
|
||||
|
||||
[Check it out on GitHub...](https://github.com/Enome/react.io)
|
||||
|
||||
|
||||
## cssobjectify
|
||||
|
||||
[Andrey Popp](http://andreypopp.com/) implemented a source transform that takes a CSS file and converts it to JSON. This integrates pretty nicely with React.
|
||||
|
||||
```javascript
|
||||
/* style.css */
|
||||
MyComponent {
|
||||
font-size: 12px;
|
||||
background-color: red;
|
||||
}
|
||||
|
||||
/* myapp.js */
|
||||
var React = require('react-tools/build/modules/React');
|
||||
var Styles = require('./styles.css');
|
||||
|
||||
var MyComponent = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div style={Styles.MyComponent}>
|
||||
Hello, world!
|
||||
</div>
|
||||
)
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
[Check it out on GitHub...](https://github.com/andreypopp/cssobjectify)
|
||||
|
||||
|
||||
## ngReact
|
||||
|
||||
[David Chang](http://davidandsuzi.com/) working at [HasOffer](http://www.hasoffers.com/) wanted to speed up his Angular app and replaced Angular primitives by React at different layers. When using React naively it is 67% faster, but when combining it with angular's transclusion it is 450% slower.
|
||||
|
||||
> Rendering this takes 803ms for 10 iterations, hovering around 35 and 55ms for each data reload (that's 67% faster). You'll notice that the first load takes a little longer than successive loads, and the second load REALLY struggles - here, it's 433ms, which is more than half of the total time!
|
||||
> <figure>[](http://davidandsuzi.com/ngreact-react-components-in-angular/)</figure>
|
||||
>
|
||||
> [Read the full article...](http://davidandsuzi.com/ngreact-react-components-in-angular/)
|
||||
|
||||
|
||||
## vim-jsx
|
||||
|
||||
[Max Wang](https://github.com/mxw) made a vim syntax highlighting and indentation plugin for vim.
|
||||
|
||||
> Syntax highlighting and indenting for JSX. JSX is a JavaScript syntax transformer which translates inline XML document fragments into JavaScript objects. It was developed by Facebook alongside React.
|
||||
>
|
||||
> This bundle requires pangloss's [vim-javascript](https://github.com/pangloss/vim-javascript) syntax highlighting.
|
||||
>
|
||||
> Vim support for inline XML in JS is remarkably similar to the same for PHP.
|
||||
>
|
||||
> [View on GitHub...](https://github.com/mxw/vim-jsx)
|
||||
|
||||
|
||||
## Random Tweet
|
||||
|
||||
<center><blockquote class="twitter-tweet" lang="en"><p>I may be starting to get annoying with this, but ReactJS is really exciting. I truly feel the virtual DOM is a game changer.</p>— Eric Florenzano (@ericflo) <a href="https://twitter.com/ericflo/statuses/413842834974732288">December 20, 2013</a></blockquote></center>
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
---
|
||||
title: "React Chrome Developer Tools"
|
||||
layout: post
|
||||
author: Sebastian Markbåge
|
||||
---
|
||||
|
||||
With the new year, we thought you'd enjoy some new tools for debugging React code. Today we're releasing the [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), an extension to the Chrome Developer Tools. [Download them from the Chrome Web Store](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi).
|
||||
|
||||
<figure><iframe width="560" height="315" src="//www.youtube.com/embed/Cey7BS6dE0M" frameborder="0" allowfullscreen></iframe></figure>
|
||||
|
||||
You will get a new tab titled "React" in your Chrome DevTools. This tab shows you a list of the root React Components that are rendered on the page as well as the subcomponents that each root renders.
|
||||
|
||||
Selecting a Component in this tab allows you to view and edit its props and state in the panel on the right. In the breadcrumbs at the bottom, you can inspect the selected Component, the Component that created it, the Component that created that one, and so on.
|
||||
|
||||
When you inspect a DOM element using the regular Elements tab, you can switch over to the React tab and the corresponding Component will be automatically selected. The Component will also be automatically selected if you have a breakpoint within its render phase. This allows you to step through the render tree and see how one Component affects another one.
|
||||
<figure>[](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi)</figure>
|
||||
|
||||
We hope these tools will help your team better understand your component hierarchy and track down bugs. We're very excited about this initial launch and appreciate any feedback you may have. As always, we also accept [pull requests on GitHub](https://github.com/facebook/react-devtools).
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
---
|
||||
title: "Community Round-up #14"
|
||||
layout: post
|
||||
author: Vjeux
|
||||
---
|
||||
|
||||
The theme of this first round-up of 2014 is integration. I've tried to assemble a list of articles and projects that use React in various environments.
|
||||
|
||||
## React Baseline
|
||||
|
||||
React is only one-piece of your web application stack. [Mark Lussier](https://github.com/intabulas) shared his baseline stack that uses React along with Grunt, Browserify, Bower, Zepto, Director and Sass. This should help you get started using React for a new project.
|
||||
|
||||
> As I do more projects with ReactJS I started to extract a baseline to use when starting new projects. This is very opinionated and I change my opinion from time to time. This is by no ways perfect and in your opinion most likely wrong :).. which is why I love github
|
||||
>
|
||||
> I encourage you to fork, and make it right and submit a pull request!
|
||||
>
|
||||
> My current opinion is using tools like Grunt, Browserify, Bower and mutiple grunt plugins to get the job done. I also opted for Zepto over jQuery and the Flatiron Project's Director when I need a router. Oh and for the last little bit of tech that makes you mad, I am in the SASS camp when it comes to stylesheets
|
||||
>
|
||||
> [Check it out on GitHub...](https://github.com/intabulas/reactjs-baseline)
|
||||
|
||||
|
||||
## Animal Sounds
|
||||
|
||||
[Josh Duck](http://joshduck.com/) used React in order to build a Windows 8 tablet app. This is a good example of a touch app written in React.
|
||||
<figure>[](http://apps.microsoft.com/windows/en-us/app/baby-play-animal-sounds/9280825c-2ed9-41c0-ba38-aa9a5b890bb9)</figure>
|
||||
|
||||
[Download the app...](http://apps.microsoft.com/windows/en-us/app/baby-play-animal-sounds/9280825c-2ed9-41c0-ba38-aa9a5b890bb9)
|
||||
|
||||
|
||||
## React Rails Tutorial
|
||||
|
||||
[Selem Delul](http://selem.im) bundled the [React Tutorial](http://facebook.github.io/react/docs/tutorial.html) into a rails app. This is a good example on how to get started with a rails project.
|
||||
|
||||
> ```
|
||||
git clone https://github.com/necrodome/react-rails-tutorial
|
||||
cd react-rails-tutorial
|
||||
bundle install
|
||||
rake db:migrate
|
||||
rails s
|
||||
```
|
||||
> Then visit http://localhost:3000/app to see the React application that is explained in the React Tutorial. Try opening multiple tabs!
|
||||
>
|
||||
> [View on GitHub...](https://github.com/necrodome/react-rails-tutorial)
|
||||
|
||||
## Mixing with Backbone
|
||||
|
||||
[Eldar Djafarov](http://eldar.djafarov.com/) implemented a mixin to link Backbone models to React state and a small abstraction to write two-way binding on-top.
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/djkojb/qZf48/13/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
|
||||
[Check out the blog post...](http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/)
|
||||
|
||||
|
||||
## React Infinite Scroll
|
||||
|
||||
[Guillaume Rivals](https://twitter.com/guillaumervls) implemented an InfiniteScroll component. This is a good example of a React component that has a simple yet powerful API.
|
||||
|
||||
```javascript
|
||||
<InfiniteScroll
|
||||
pageStart={0}
|
||||
loadMore={loadFunc}
|
||||
hasMore={true || false}
|
||||
loader={<div className="loader">Loading ...</div>}>
|
||||
{items} // <-- This is the "stuff" you want to load
|
||||
</InfiniteScroll>
|
||||
```
|
||||
|
||||
[Try it out on GitHub!](https://github.com/guillaumervls/react-infinite-scroll)
|
||||
|
||||
|
||||
## Web Components Style
|
||||
|
||||
[Thomas Aylott](http://subtlegradient.com/) implemented an API that looks like Web Components but using React underneath.
|
||||
|
||||
<iframe width="100%" height="300" src="http://jsfiddle.net/SubtleGradient/ue2Aa/embedded/html,js,result" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
|
||||
|
||||
|
||||
## React vs Angular
|
||||
|
||||
React is often compared with Angular. [Pete Hunt](http://skulbuny.com/2013/10/31/react-vs-angular/) wrote an opinionated post on the subject.
|
||||
|
||||
> First of all I think it’s important to evaluate technologies on objective rather than subjective features. “It feels nicer” or “it’s cleaner” aren’t valid reasons: performance, modularity, community size and ease of testing / integration with other tools are.
|
||||
>
|
||||
> I’ve done a lot of work benchmarking, building apps, and reading the code of Angular to try to come up with a reasonable comparison between their ways of doing things.
|
||||
>
|
||||
> [Read the full post...](http://skulbuny.com/2013/10/31/react-vs-angular/)
|
||||
|
||||
|
||||
|
||||
## Random Tweet
|
||||
|
||||
<div><blockquote class="twitter-tweet" lang="en"><p>Really intrigued by React.js. I've looked at all JS frameworks, and excepting <a href="https://twitter.com/serenadejs">@serenadejs</a> this is the first one which makes sense to me.</p>— Jonas Nicklas (@jonicklas) <a href="https://twitter.com/jonicklas/statuses/412640708755869696">December 16, 2013</a></blockquote></div>
|
||||
@@ -1,126 +0,0 @@
|
||||
---
|
||||
title: "Community Round-up #15"
|
||||
layout: post
|
||||
author: Jonas Gebhardt
|
||||
---
|
||||
|
||||
Interest in React seems to have surged ever since David Nolen ([@swannodette](https://twitter.com/swannodette))'s introduction of [Om](https://github.com/swannodette/om) in his post ["The Future of Javascript MVC Frameworks"](http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/).
|
||||
|
||||
In this React Community Round-up, we are taking a closer look at React from a functional programming perspective.
|
||||
|
||||
## "React: Another Level of Indirection"
|
||||
To start things off, Eric Normand ([@ericnormand](https://twitter.com/ericnormand)) of [LispCast](http://lispcast.com) makes the case for [React from a general functional programming standpoint](http://www.lispcast.com/react-another-level-of-indirection) and explains how React's "Virtual DOM provides the last piece of the Web Frontend Puzzle for ClojureScript".
|
||||
|
||||
> The Virtual DOM is an indirection mechanism that solves the difficult problem of DOM programming: how to deal with incremental changes to a stateful tree structure. By abstracting away the statefulness, the Virtual DOM turns the real DOM into an immediate mode GUI, which is perfect for functional programming.
|
||||
>
|
||||
> [Read the full post...](http://www.lispcast.com/react-another-level-of-indirection)
|
||||
|
||||
## Reagent: Minimalistic React for ClojureScript
|
||||
Dan Holmsand ([@holmsand](https://twitter.com/holmsand)) created [Reagent](http://holmsand.github.io/reagent/), a simplistic ClojureScript API to React.
|
||||
|
||||
> It allows you to define efficient React components using nothing but plain ClojureScript functions and data, that describe your UI using a Hiccup-like syntax.
|
||||
>
|
||||
> The goal of Reagent is to make it possible to define arbitrarily complex UIs using just a couple of basic concepts, and to be fast enough by default that you rarely have to care about performance.
|
||||
>
|
||||
> [Check it out on Github...](http://holmsand.github.io/reagent/)
|
||||
|
||||
|
||||
## Functional DOM programming
|
||||
|
||||
React's one-way data-binding naturally lends itself to a functional programming approach. Facebook's Pete Hunt ([@floydophone](https://twitter.com/floydophone)) explores how one would go about [writing web apps in a functional manner](https://medium.com/p/67d81637d43). Spoiler alert:
|
||||
|
||||
> This is React. It’s not about templates, or data binding, or DOM manipulation. It’s about using functional programming with a virtual DOM representation to build ambitious, high-performance apps with JavaScript.
|
||||
>
|
||||
> [Read the full post...](https://medium.com/p/67d81637d43)
|
||||
|
||||
Pete also explains this in detail at his #MeteorDevShop talk (about 30 Minutes):
|
||||
|
||||
<iframe width="560" height="315" src="//www.youtube.com/embed/Lqcs6hPOcFw?start=2963" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
|
||||
|
||||
## Kioo: Separating markup and logic
|
||||
[Creighton Kirkendall](https://github.com/ckirkendall) created [Kioo](https://github.com/ckirkendall/kioo), which adds Enlive-style templating to React. HTML templates are separated from the application logic. Kioo comes with separate examples for both Om and Reagent.
|
||||
|
||||
A basic example from github:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<body>
|
||||
<header>
|
||||
<h1>Header placeholder</h1>
|
||||
<ul id="navigation">
|
||||
<li class="nav-item"><a href="#">Placeholder</a></li>
|
||||
</ul>
|
||||
</header>
|
||||
<div class="content">place holder</div>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
```clojure
|
||||
...
|
||||
|
||||
(defn my-nav-item [[caption func]]
|
||||
(kioo/component "main.html" [:.nav-item]
|
||||
{[:a] (do-> (content caption)
|
||||
(set-attr :onClick func))}))
|
||||
|
||||
(defn my-header [heading nav-elms]
|
||||
(kioo/component "main.html" [:header]
|
||||
{[:h1] (content heading)
|
||||
[:ul] (content (map my-nav-item nav-elms))}))
|
||||
|
||||
(defn my-page [data]
|
||||
(kioo/component "main.html"
|
||||
{[:header] (substitute (my-header (:heading data)
|
||||
(:navigation data)))
|
||||
[:.content] (content (:content data))}))
|
||||
|
||||
(def app-state (atom {:heading "main"
|
||||
:content "Hello World"
|
||||
:navigation [["home" #(js/alert %)]
|
||||
["next" #(js/alert %)]]}))
|
||||
|
||||
(om/root app-state my-page (.-body js/document))
|
||||
```
|
||||
|
||||
## Om
|
||||
|
||||
In an interview with David Nolen, Tom Coupland ([@tcoupland](https://twitter.com/tcoupland)) of InfoQ provides a nice summary of recent developments around Om ("[Om: Enhancing Facebook's React with Immutability](http://www.infoq.com/news/2014/01/om-react)").
|
||||
|
||||
> David [Nolen]: I think people are starting to see the limitations of just JavaScript and jQuery and even more structured solutions like Backbone, Angular, Ember, etc. React is a fresh approach to the DOM problem that seems obvious in hindsight.
|
||||
>
|
||||
> [Read the full interview...](http://www.infoq.com/news/2014/01/om-react)
|
||||
|
||||
### A slice of React, ClojureScript and Om
|
||||
|
||||
Fredrik Dyrkell ([@lexicallyscoped](https://twitter.com/lexicallyscoped)) rewrote part of the [React tutorial in both ClojureScript and Om](http://www.lexicallyscoped.com/2013/12/25/slice-of-reactjs-and-cljs.html), along with short, helpful explanations.
|
||||
|
||||
> React has sparked a lot of interest in the Clojure community lately [...]. At the very core, React lets you build up your DOM representation in a functional fashion by composing pure functions and you have a simple building block for everything: React components.
|
||||
>
|
||||
> [Read the full post...](http://www.lexicallyscoped.com/2013/12/25/slice-of-reactjs-and-cljs.html)
|
||||
|
||||
In a separate post, Dyrkell breaks down [how to build a binary clock component](http://www.lexicallyscoped.com/2014/01/23/ClojureScript-react-om-binary-clock.html) in Om.
|
||||
|
||||
[[Demo](http://www.lexicallyscoped.com/demo/binclock/)] [[Code](https://github.com/fredyr/binclock/blob/master/src/binclock/core.cljs)]
|
||||
|
||||
### Time Travel: Implementing undo in Om
|
||||
David Nolen shows how to leverage immutable data structures to [add global undo](http://swannodette.github.io/2013/12/31/time-travel/) functionality to an app – using just 13 lines of ClojureScript.
|
||||
|
||||
### A Step-by-Step Om Walkthrough
|
||||
|
||||
[Josh Lehman](http://www.joshlehman.me) took the time to create an extensive [step-by-step walkthrough](http://www.joshlehman.me/rewriting-the-react-tutorial-in-om/) of the React tutorial in Om. The well-documented source is on [github](https://github.com/jalehman/omtut-starter).
|
||||
|
||||
### Omkara
|
||||
|
||||
[brendanyounger](https://github.com/brendanyounger) created [omkara](https://github.com/brendanyounger/omkara), a starting point for ClojureScript web apps based on Om/React. It aims to take advantage of server-side rendering and comes with a few tips on getting started with Om/React projects.
|
||||
|
||||
### Om Experience Report
|
||||
Adam Solove ([@asolove](https://twitter.com/asolove/)) [dives a little deeper into Om, React and ClojureScript](http://adamsolove.com/js/clojure/2014/01/06/om-experience-report.html). He shares some helpful tips he gathered while building his [CartoCrayon](https://github.com/asolove/carto-crayon) prototype.
|
||||
|
||||
## Not-so-random Tweet
|
||||
|
||||
|
||||
<div><blockquote class="twitter-tweet" lang="en"><p>[@swannodette](https://twitter.com/swannodette) No thank you! It's honestly a bit weird because Om is exactly what I didn't know I wanted for doing functional UI work.</p>— Adam Solove (@asolove) <a href="https://twitter.com/asolove/status/420294067637858304">January 6, 2014</a></blockquote></div>
|
||||
@@ -1,86 +0,0 @@
|
||||
---
|
||||
title: "Community Round-up #16"
|
||||
layout: post
|
||||
author: Jonas Gebhardt
|
||||
---
|
||||
|
||||
There have been many posts recently covering the <i>why</i> and <i>how</i> of React. This week's community round-up includes a collection of recent articles to help you get started with React, along with a few posts that explain some of the inner workings.
|
||||
|
||||
|
||||
## React in a nutshell
|
||||
Got five minutes to pitch React to your coworkers? John Lynch ([@johnrlynch](https://twitter.com/johnrlynch)) put together [this excellent and refreshing slideshow](http://slid.es/johnlynch/reactjs):
|
||||
|
||||
<iframe src="//slid.es/johnlynch/reactjs/embed" width="576" height="420" scrolling="no" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
|
||||
|
||||
|
||||
|
||||
## React's diff algorithm
|
||||
|
||||
React core team member Christopher Chedeau ([@vjeux](https://twitter.com/vjeux)) explores the innards of React's tree diffing algorithm in this [extensive and well-illustrated post](http://calendar.perfplanet.com/2013/diff/). <figure>[](http://calendar.perfplanet.com/2013/diff/)</figure>
|
||||
|
||||
While we're talking about tree diffing: Matt Esch ([@MatthewEsch](https://twitter.com/MatthewEsch)) created [this project](https://github.com/Matt-Esch/virtual-dom), which aims to implement the virtual DOM and a corresponding diff algorithm as separate modules.
|
||||
|
||||
|
||||
|
||||
|
||||
## Many, many new introductions to React!
|
||||
|
||||
|
||||
|
||||
James Padosley wrote a short post on the basics (and merits) of React: [What is React?](http://james.padolsey.com/javascript/what-is-react/)
|
||||
> What I like most about React is that it doesn't impose heady design patterns and data-modelling abstractions on me. [...] Its opinions are so minimal and its abstractions so focused on the problem of the DOM, that you can merrily slap your design choices atop.
|
||||
|
||||
> [Read the full post...](http://james.padolsey.com/javascript/what-is-react/)
|
||||
|
||||
Taylor Lapeyre ([@taylorlapeyre](https://twitter.com/taylorlapeyre)) wrote another nice [introduction to React](http://words.taylorlapeyre.me/an-introduction-to-react).
|
||||
|
||||
> React expects you to do the work of getting and pushing data from the server. This makes it very easy to implement React as a front end solution, since it simply expects you to hand it data. React does all the other work.
|
||||
|
||||
> [Read the full post...](http://words.taylorlapeyre.me/an-introduction-to-react)
|
||||
|
||||
|
||||
[This "Deep explanation for newbies"](http://www.webdesignporto.com/react-js-in-pure-javascript-facebook-library/?utm_source=echojs&utm_medium=post&utm_campaign=echojs) by [@ProJavaScript](https://twitter.com/ProJavaScript) explains how to get started building a React game without using the optional JSX syntax.
|
||||
|
||||
### React around the world
|
||||
|
||||
It's great to see the React community expand internationally. [This site](http://habrahabr.ru/post/189230/) features a React introduction in Russian.
|
||||
|
||||
### React tutorial series
|
||||
|
||||
[Christopher Pitt](https://medium.com/@followchrisp) explains [React Components](https://medium.com/react-tutorials/828c397e3dc8) and [React Properties](https://medium.com/react-tutorials/ef11cd55caa0). The former includes a nice introduction to using JSX, while the latter focuses on adding interactivity and linking multiple components together. Also check out the [other posts in his React Tutorial series](https://medium.com/react-tutorials), e.g. on using [React + Backbone Model](https://medium.com/react-tutorials/8aaec65a546c) and [React + Backbone Router](https://medium.com/react-tutorials/c00be0cf1592).
|
||||
|
||||
### Beginner tutorial: Implementing the board game Go
|
||||
|
||||
[Chris LaRose](http://cjlarose.com/) walks through the steps of creating a Go app in React, showing how to separate application logic from the rendered components. Check out his [tutorial](http://cjlarose.com/2014/01/09/react-board-game-tutorial.html) or go straight to the [code](https://github.com/cjlarose/react-go).
|
||||
|
||||
### Egghead.io video tutorials
|
||||
|
||||
Joe Maddalone ([@joemaddalone](https://twitter.com/joemaddalone)) of [egghead.io](https://egghead.io/) created a series of React video tutorials, such as [this](http://www.youtube.com/watch?v=rFvZydtmsxM&feature=youtu.be&a) introduction to React Components. [[part 1](http://www.youtube.com/watch?v=rFvZydtmsxM&feature=youtu.be&a)], [[part 2](http://www.youtube.com/watch?v=5yvFLrt7N8M)]
|
||||
|
||||
### "React: Finally, a great server/client web stack"
|
||||
|
||||
Eric Florenzano ([@ericflo](https://twitter.com/ericflo)) sheds some light on what makes React perfect for server rendering:
|
||||
|
||||
> [...] the ideal solution would fully render the markup on the server, deliver it to the client so that it can be shown to the user instantly. Then it would asynchronously load some Javascript that would attach to the rendered markup, and invisibly promote the page into a full app that can render its own markup. [...]
|
||||
|
||||
> What I've discovered is that enough of the pieces have come together, that this futuristic-sounding web environment is actually surprisingly easy to do now with React.js.
|
||||
|
||||
> [Read the full post...](http://eflorenzano.com/blog/2014/01/23/react-finally-server-client/)
|
||||
|
||||
## Building a complex React component
|
||||
[Matt Harrison](http://matt-harrison.com/) walks through the process of [creating an SVG-based Resistance Calculator](http://matt-harrison.com/building-a-complex-web-component-with-facebooks-react-library/) using React. <figure>[](http://matt-harrison.com/building-a-complex-web-component-with-facebooks-react-library/)</figure>
|
||||
|
||||
|
||||
|
||||
## Random Tweets
|
||||
|
||||
<div><blockquote class="twitter-tweet" lang="en"><p>[#reactjs](https://twitter.com/search?q=%23reactjs&src=hash) has very simple API, but it's amazing how much work has been done under the hood to make it blazing fast.</p>— Anton Astashov (@anton_astashov) <a href="https://twitter.com/anton_astashov/status/417556491646693378">December 30, 2013</a></blockquote></div>
|
||||
|
||||
<div><blockquote class="twitter-tweet" lang="en"><p>[#reactjs]((https://twitter.com/search?q=%23reactjs&src=hash) makes refactoring your HTML as easy & natural as refactoring your javascript [@react_js](https://twitter.com/react_js)</p>— Jared Forsyth (@jaredforsyth) <a href="https://twitter.com/jaredforsyth/status/420304083010854912">January 6, 2014</a></blockquote></div>
|
||||
|
||||
<div><blockquote class="twitter-tweet" lang="en"><p>Played with react.js for an hour, so many things suddenly became stupidly simple.</p>— andrewingram (@andrewingram) <a href="https://twitter.com/andrewingram/status/422810480701620225">January 13, 2014</a></blockquote></div>
|
||||
|
||||
<div><blockquote class="twitter-tweet" lang="en"><p>[@okonetchnikov](https://twitter.com/okonetchnikov) HOLY CRAP react is nice</p>— julik (@julikt) <a href="https://twitter.com/julikt/status/422843478792765440">January 13, 2014</a></blockquote></div>
|
||||
|
||||
<div><blockquote class="twitter-tweet" lang="en"><p>brb rewriting everything with react
|
||||
</p>— Ben Smithett (@bensmithett) <a href="https://twitter.com/bensmithett/status/430671242186592256">February 4, 2014</a></blockquote></div>
|
||||
@@ -1,132 +0,0 @@
|
||||
---
|
||||
title: React v0.9 RC
|
||||
layout: post
|
||||
author: Ben Alpert
|
||||
---
|
||||
|
||||
We're almost ready to release React v0.9! We're posting a release candidate so that you can test your apps on it; we'd much prefer to find show-stopping bugs now rather than after we release.
|
||||
|
||||
The release candidate is available for download from the CDN:
|
||||
|
||||
* **React**
|
||||
Dev build with warnings: <http://fb.me/react-0.9.0-rc1.js>
|
||||
Minified build for production: <http://fb.me/react-0.9.0-rc1.min.js>
|
||||
* **React with Add-Ons**
|
||||
Dev build with warnings: <http://fb.me/react-with-addons-0.9.0-rc1.js>
|
||||
Minified build for production: <http://fb.me/react-with-addons-0.9.0-rc1.min.js>
|
||||
* **In-Browser JSX transformer**
|
||||
<http://fb.me/JSXTransformer-0.9.0-rc1.js>
|
||||
|
||||
We've also published version `0.9.0-rc1` of the `react` and `react-tools` packages on npm and the `react` package on bower.
|
||||
|
||||
Please try these builds out and [file an issue on GitHub](https://github.com/facebook/react/issues/new) if you see anything awry.
|
||||
|
||||
## Upgrade Notes
|
||||
|
||||
In addition to the changes to React core listed below, we've made a small change to the way JSX interprets whitespace to make things more consistent. With this release, space between two components on the same line will be preserved, while a newline separating a text node from a tag will be eliminated in the output. Consider the code:
|
||||
|
||||
```html
|
||||
<div>
|
||||
Monkeys:
|
||||
{listOfMonkeys} {submitButton}
|
||||
</div>
|
||||
```
|
||||
|
||||
In v0.8 and below, it was transformed to the following:
|
||||
|
||||
```javascript
|
||||
React.DOM.div(null,
|
||||
" Monkeys: ",
|
||||
listOfMonkeys, submitButton
|
||||
)
|
||||
```
|
||||
|
||||
In v0.9, it will be transformed to this JS instead:
|
||||
|
||||
```javascript{2,3}
|
||||
React.DOM.div(null,
|
||||
"Monkeys:",
|
||||
listOfMonkeys, " ", submitButton
|
||||
)
|
||||
```
|
||||
|
||||
We believe this new behavior is more helpful and elimates cases where unwanted whitespace was previously added.
|
||||
|
||||
In cases where you want to preserve the space adjacent to a newline, you can write a JS string like `{"Monkeys: "}` in your JSX source. We've included a script to do an automated codemod of your JSX source tree that preserves the old whitespace behavior by adding and removing spaces appropriately. You can [install jsx\_whitespace\_transformer from npm](https://github.com/facebook/react/blob/master/npm-jsx_whitespace_transformer/README.md) and run it over your source tree to modify files in place. The transformed JSX files will preserve your code's existing whitespace behavior.
|
||||
|
||||
## Changelog
|
||||
|
||||
### React Core
|
||||
|
||||
#### Breaking Changes
|
||||
|
||||
- The lifecycle methods `componentDidMount` and `componentDidUpdate` no longer receive the root node as a parameter; use `this.getDOMNode()` instead
|
||||
- Whenever a prop is equal to `undefined`, the default value returned by `getDefaultProps` will now be used instead
|
||||
- `React.unmountAndReleaseReactRootNode` was previously deprecated and has now been removed
|
||||
- `React.renderComponentToString` is now synchronous and returns the generated HTML string
|
||||
- Full-page rendering (that is, rendering the `<html>` tag using React) is now supported only when starting with server-rendered markup
|
||||
- On mouse wheel events, `deltaY` is no longer negated
|
||||
- When prop types validation fails, a warning is logged instead of an error thrown (with the production build of React, the type checks are now skipped for performance)
|
||||
- On `input`, `select`, and `textarea` elements, `.getValue()` is no longer supported; use `.getDOMNode().value` instead
|
||||
|
||||
#### New Features
|
||||
|
||||
- React now never rethrows errors, so stack traces are more accurate and Chrome's purple break-on-error stop sign now works properly
|
||||
- Added a new tool for profiling React components and identifying places where defining `shouldComponentUpdate` can give performance improvements
|
||||
- Added support for SVG tags `defs`, `linearGradient`, `polygon`, `radialGradient`, `stop`
|
||||
- Added support for more attributes:
|
||||
- `noValidate` and `formNoValidate` for forms
|
||||
- `property` for Open Graph `<meta>` tags
|
||||
- `sandbox`, `seamless`, and `srcDoc` for `<iframe>` tags
|
||||
- `scope` for screen readers
|
||||
- `span` for `<colgroup>` tags
|
||||
- Added support for defining `propTypes` in mixins
|
||||
- Added `any`, `arrayOf`, `component`, `oneOfType`, `renderable`, `shape` to `React.PropTypes`
|
||||
- Added support for `statics` on component spec for static component methods
|
||||
- On all events, `.currentTarget` is now properly set
|
||||
- On keyboard events, `.key` is now polyfilled in all browsers for special (non-printable) keys
|
||||
- On clipboard events, `.clipboardData` is now polyfilled in IE
|
||||
- On drag events, `.dragTransfer` is now present
|
||||
- Added support for `onMouseOver` and `onMouseOut` in addition to the existing `onMouseEnter` and `onMouseLeave` events
|
||||
- Added support for `onLoad` and `onError` on `<img>` elements
|
||||
- Added support for `onReset` on `<form>` elements
|
||||
- The `autoFocus` attribute is now polyfilled consistently on `input`, `select`, and `textarea`
|
||||
|
||||
#### Bug Fixes
|
||||
|
||||
- React no longer adds an `__owner__` property to each component's `props` object; passed-in props are now never mutated
|
||||
- When nesting top-level components (e.g., calling `React.renderComponent` within `componentDidMount`), events now properly bubble to the parent component
|
||||
- Fixed a case where nesting top-level components would throw an error when updating
|
||||
- Passing an invalid or misspelled propTypes type now throws an error
|
||||
- On mouse enter/leave events, `.target`, `.relatedTarget`, and `.type` are now set properly
|
||||
- On composition events, `.data` is now properly normalized in IE9 and IE10
|
||||
- CSS property values no longer have `px` appended for the unitless properties `columnCount`, `flex`, `flexGrow`, `flexShrink`, `lineClamp`, `order`, `widows`
|
||||
- Fixed a memory leak when unmounting children with a `componentWillUnmount` handler
|
||||
- Fixed a memory leak when `renderComponentToString` would store event handlers
|
||||
- Fixed an error that could be thrown when removing form elements during a click handler
|
||||
- `key` values containing `.` are now supported
|
||||
- Shortened `data-reactid` values for performance
|
||||
- Components now always remount when the `key` property changes
|
||||
- Event handlers are attached to `document` only when necessary, improving performance in some cases
|
||||
- Events no longer use `.returnValue` in modern browsers, eliminating a warning in Chrome
|
||||
- `scrollLeft` and `scrollTop` are no longer accessed on document.body, eliminating a warning in Chrome
|
||||
- General performance fixes, memory optimizations, improvements to warnings and error messages
|
||||
|
||||
### React with Addons
|
||||
|
||||
- `React.addons.TransitionGroup` was renamed to `React.addons.CSSTransitionGroup`
|
||||
- `React.addons.TransitionGroup` was added as a more general animation wrapper
|
||||
- `React.addons.cloneWithProps` was added for cloning components and modifying their props
|
||||
- Bug fix for adding back nodes during an exit transition for CSSTransitionGroup
|
||||
- Bug fix for changing `transitionLeave` in CSSTransitionGroup
|
||||
- Performance optimizations for CSSTransitionGroup
|
||||
- On checkbox `<input>` elements, `checkedLink` is now supported for two-way binding
|
||||
|
||||
### JSX Compiler and react-tools Package
|
||||
|
||||
- Whitespace normalization has changed; now space between two tags on the same line will be preserved, while newlines between two tags will be removed
|
||||
- The `react-tools` npm package no longer includes the React core libraries; use the `react` package instead.
|
||||
- `displayName` is now added in more cases, improving error messages and names in the React Dev Tools
|
||||
- Fixed an issue where an invalid token error was thrown after a JSX closing tag
|
||||
- `JSXTransformer` now uses source maps automatically in modern browsers
|
||||
- `JSXTransformer` error messages now include the filename and problematic line contents when a file fails to parse
|
||||
@@ -1,144 +0,0 @@
|
||||
---
|
||||
title: React v0.9
|
||||
layout: post
|
||||
author: Ben Alpert
|
||||
---
|
||||
|
||||
I'm excited to announce that today we're releasing React v0.9, which incorporates many bug fixes and several new features since the last release. This release contains almost four months of work, including over 800 commits from over 70 committers!
|
||||
|
||||
Thanks to everyone who tested the release candidate; we were able to find and fix an error in the event handling code, we upgraded envify to make running browserify on React faster, and we added support for five new attributes.
|
||||
|
||||
As always, the release is available for download from the CDN:
|
||||
|
||||
* **React**
|
||||
Dev build with warnings: <http://fb.me/react-0.9.0.js>
|
||||
Minified build for production: <http://fb.me/react-0.9.0.min.js>
|
||||
* **React with Add-Ons**
|
||||
Dev build with warnings: <http://fb.me/react-with-addons-0.9.0.js>
|
||||
Minified build for production: <http://fb.me/react-with-addons-0.9.0.min.js>
|
||||
* **In-Browser JSX Transformer**
|
||||
<http://fb.me/JSXTransformer-0.9.0.js>
|
||||
|
||||
We've also published version `0.9.0` of the `react` and `react-tools` packages on npm and the `react` package on bower.
|
||||
|
||||
## What’s New?
|
||||
|
||||
This version includes better support for normalizing event properties across all supported browsers so that you need to worry even less about cross-browser differences. We've also made many improvements to error messages and have refactored the core to never rethrow errors, so stack traces are more accurate and Chrome's purple break-on-error stop sign now works properly.
|
||||
|
||||
We've also added to the add-ons build [React.addons.TestUtils](/react/docs/test-utils.html), a set of new utilities to help you write unit tests for React components. You can now simulate events on your components, and several helpers are provided to help make assertions about the rendered DOM tree.
|
||||
|
||||
We've also made several other improvements and a few breaking changes; the full changelog is provided below.
|
||||
|
||||
## JSX Whitespace
|
||||
|
||||
In addition to the changes to React core listed below, we've made a small change to the way JSX interprets whitespace to make things more consistent. With this release, space between two components on the same line will be preserved, while a newline separating a text node from a tag will be eliminated in the output. Consider the code:
|
||||
|
||||
```html
|
||||
<div>
|
||||
Monkeys:
|
||||
{listOfMonkeys} {submitButton}
|
||||
</div>
|
||||
```
|
||||
|
||||
In v0.8 and below, it was transformed to the following:
|
||||
|
||||
```javascript
|
||||
React.DOM.div(null,
|
||||
" Monkeys: ",
|
||||
listOfMonkeys, submitButton
|
||||
)
|
||||
```
|
||||
|
||||
In v0.9, it will be transformed to this JS instead:
|
||||
|
||||
```javascript{2,3}
|
||||
React.DOM.div(null,
|
||||
"Monkeys:",
|
||||
listOfMonkeys, " ", submitButton
|
||||
)
|
||||
```
|
||||
|
||||
We believe this new behavior is more helpful and elimates cases where unwanted whitespace was previously added.
|
||||
|
||||
In cases where you want to preserve the space adjacent to a newline, you can write `{'Monkeys: '}` or `Monkeys:{' '}` in your JSX source. We've included a script to do an automated codemod of your JSX source tree that preserves the old whitespace behavior by adding and removing spaces appropriately. You can [install jsx\_whitespace\_transformer from npm](https://github.com/facebook/react/blob/master/npm-jsx_whitespace_transformer/README.md) and run it over your source tree to modify files in place. The transformed JSX files will preserve your code's existing whitespace behavior.
|
||||
|
||||
## Changelog
|
||||
|
||||
### React Core
|
||||
|
||||
#### Breaking Changes
|
||||
|
||||
- The lifecycle methods `componentDidMount` and `componentDidUpdate` no longer receive the root node as a parameter; use `this.getDOMNode()` instead
|
||||
- Whenever a prop is equal to `undefined`, the default value returned by `getDefaultProps` will now be used instead
|
||||
- `React.unmountAndReleaseReactRootNode` was previously deprecated and has now been removed
|
||||
- `React.renderComponentToString` is now synchronous and returns the generated HTML string
|
||||
- Full-page rendering (that is, rendering the `<html>` tag using React) is now supported only when starting with server-rendered markup
|
||||
- On mouse wheel events, `deltaY` is no longer negated
|
||||
- When prop types validation fails, a warning is logged instead of an error thrown (with the production build of React, type checks are now skipped for performance)
|
||||
- On `input`, `select`, and `textarea` elements, `.getValue()` is no longer supported; use `.getDOMNode().value` instead
|
||||
|
||||
#### New Features
|
||||
|
||||
- React now never rethrows errors, so stack traces are more accurate and Chrome's purple break-on-error stop sign now works properly
|
||||
- Added support for SVG tags `defs`, `linearGradient`, `polygon`, `radialGradient`, `stop`
|
||||
- Added support for more attributes:
|
||||
- `crossOrigin` for CORS requests
|
||||
- `download` and `hrefLang` for `<a>` tags
|
||||
- `mediaGroup` and `muted` for `<audio>` and `<video>` tags
|
||||
- `noValidate` and `formNoValidate` for forms
|
||||
- `property` for Open Graph `<meta>` tags
|
||||
- `sandbox`, `seamless`, and `srcDoc` for `<iframe>` tags
|
||||
- `scope` for screen readers
|
||||
- `span` for `<colgroup>` tags
|
||||
- Added support for defining `propTypes` in mixins
|
||||
- Added `any`, `arrayOf`, `component`, `oneOfType`, `renderable`, `shape` to `React.PropTypes`
|
||||
- Added support for `statics` on component spec for static component methods
|
||||
- On all events, `.currentTarget` is now properly set
|
||||
- On keyboard events, `.key` is now polyfilled in all browsers for special (non-printable) keys
|
||||
- On clipboard events, `.clipboardData` is now polyfilled in IE
|
||||
- On drag events, `.dragTransfer` is now present
|
||||
- Added support for `onMouseOver` and `onMouseOut` in addition to the existing `onMouseEnter` and `onMouseLeave` events
|
||||
- Added support for `onLoad` and `onError` on `<img>` elements
|
||||
- Added support for `onReset` on `<form>` elements
|
||||
- The `autoFocus` attribute is now polyfilled consistently on `input`, `select`, and `textarea`
|
||||
|
||||
#### Bug Fixes
|
||||
|
||||
- React no longer adds an `__owner__` property to each component's `props` object; passed-in props are now never mutated
|
||||
- When nesting top-level components (e.g., calling `React.renderComponent` within `componentDidMount`), events now properly bubble to the parent component
|
||||
- Fixed a case where nesting top-level components would throw an error when updating
|
||||
- Passing an invalid or misspelled propTypes type now throws an error
|
||||
- On mouse enter/leave events, `.target`, `.relatedTarget`, and `.type` are now set properly
|
||||
- On composition events, `.data` is now properly normalized in IE9 and IE10
|
||||
- CSS property values no longer have `px` appended for the unitless properties `columnCount`, `flex`, `flexGrow`, `flexShrink`, `lineClamp`, `order`, `widows`
|
||||
- Fixed a memory leak when unmounting children with a `componentWillUnmount` handler
|
||||
- Fixed a memory leak when `renderComponentToString` would store event handlers
|
||||
- Fixed an error that could be thrown when removing form elements during a click handler
|
||||
- Boolean attributes such as `disabled` are rendered without a value (previously `disabled="true"`, now simply `disabled`)
|
||||
- `key` values containing `.` are now supported
|
||||
- Shortened `data-reactid` values for performance
|
||||
- Components now always remount when the `key` property changes
|
||||
- Event handlers are attached to `document` only when necessary, improving performance in some cases
|
||||
- Events no longer use `.returnValue` in modern browsers, eliminating a warning in Chrome
|
||||
- `scrollLeft` and `scrollTop` are no longer accessed on document.body, eliminating a warning in Chrome
|
||||
- General performance fixes, memory optimizations, improvements to warnings and error messages
|
||||
|
||||
### React with Addons
|
||||
|
||||
- `React.addons.TestUtils` was added to help write unit tests
|
||||
- `React.addons.TransitionGroup` was renamed to `React.addons.CSSTransitionGroup`
|
||||
- `React.addons.TransitionGroup` was added as a more general animation wrapper
|
||||
- `React.addons.cloneWithProps` was added for cloning components and modifying their props
|
||||
- Bug fix for adding back nodes during an exit transition for CSSTransitionGroup
|
||||
- Bug fix for changing `transitionLeave` in CSSTransitionGroup
|
||||
- Performance optimizations for CSSTransitionGroup
|
||||
- On checkbox `<input>` elements, `checkedLink` is now supported for two-way binding
|
||||
|
||||
### JSX Compiler and react-tools Package
|
||||
|
||||
- Whitespace normalization has changed; now space between two tags on the same line will be preserved, while newlines between two tags will be removed
|
||||
- The `react-tools` npm package no longer includes the React core libraries; use the `react` package instead.
|
||||
- `displayName` is now added in more cases, improving error messages and names in the React Dev Tools
|
||||
- Fixed an issue where an invalid token error was thrown after a JSX closing tag
|
||||
- `JSXTransformer` now uses source maps automatically in modern browsers
|
||||
- `JSXTransformer` error messages now include the filename and problematic line contents when a file fails to parse
|
||||
@@ -19,7 +19,7 @@ Let's look at a really simple example. Create a `hello-react.html` file with the
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello React</title>
|
||||
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="http://fb.me/react-{{site.react_version}}.min.js"></script>
|
||||
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
@@ -84,8 +84,8 @@ We've found that the best solution for this problem is to generate markup direct
|
||||
|
||||
**JSX lets you write JavaScript function calls with HTML syntax.** To generate a link in React using pure JavaScript you'd write: `React.DOM.a({href: 'http://facebook.github.io/react/'}, 'Hello React!')`. With JSX this becomes `<a href="http://facebook.github.io/react/">Hello React!</a>`. We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.**
|
||||
|
||||
JSX is very small; the "hello, world" example above uses every feature of JSX. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
|
||||
JSX is very small; the "hello, world" example above uses every feature of JSX. To learn more about it, see [JSX in depth](./jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
|
||||
|
||||
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
|
||||
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](./jsx-gotchas.html) for some key differences.
|
||||
|
||||
The easiest way to get started with JSX is to use the in-browser `JSXTransformer`. We strongly recommend that you don't use this in production. You can precompile your code using our command-line [react-tools](http://npmjs.org/package/react-tools) package.
|
||||
|
||||
@@ -10,11 +10,6 @@ next: jsx-gotchas.html
|
||||
JSX is a JavaScript XML syntax transform recommended for use
|
||||
with React.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> Don't forget the `/** @jsx React.DOM */` pragma at the beginning of your file! This tells JSX to process the file for React.
|
||||
>
|
||||
> If you don't include the pragma, your source will remain untouched, so it's safe to run the JSX transformer on all JS files in your codebase if you want to.
|
||||
|
||||
## Why JSX?
|
||||
|
||||
@@ -58,11 +53,9 @@ var app = Nav({color:"blue"}, Profile(null, "click"));
|
||||
```
|
||||
|
||||
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
|
||||
desugars into native JavaScript, and the
|
||||
[HTML to JSX converter](/react/html-jsx.html) to convert your existing HTML to
|
||||
JSX.
|
||||
desugars into native JavaScript.
|
||||
|
||||
If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows
|
||||
If you want to use JSX, the [Getting Started](getting-started.html) guide shows
|
||||
how to setup compilation.
|
||||
|
||||
> Note:
|
||||
@@ -99,10 +92,7 @@ var MyComponent = React.createClass({/*...*/});
|
||||
var app = <MyComponent someProperty={true} />;
|
||||
```
|
||||
|
||||
JSX will infer the component's name from the variable assignment and specify
|
||||
the class's [displayName](/react/docs/component-specs.html#displayName) accordingly.
|
||||
|
||||
See [Multiple Components](/react/docs/multiple-components.html) to learn more about using composite components.
|
||||
See [Multiple Components](multiple-components.html) to learn more about using composite components.
|
||||
|
||||
> Note:
|
||||
>
|
||||
@@ -178,4 +168,4 @@ efforts include:
|
||||
* JSX neither provides nor requires a runtime library.
|
||||
* JSX does not alter or add to the semantics of JavaScript.
|
||||
|
||||
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
|
||||
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](./jsx-gotchas.html) for some key differences.
|
||||
|
||||
@@ -11,7 +11,18 @@ JSX looks like HTML but there are some important differences you may run into.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> For DOM differences, such as the inline `style` attribute, check [here](/react/docs/dom-differences.html).
|
||||
> For DOM differences, such as the inline `style` attribute, check [here](dom-differences.html).
|
||||
|
||||
## Whitespace Removal
|
||||
|
||||
JSX doesn't follow the same whitespace elimination rules as HTML. JSX removes all whitespace between two curly braces expressions. If you want to have whitespace, simply add `{' '}`.
|
||||
|
||||
```javascript
|
||||
<div>{this.props.name} {' '} {this.props.surname}</div>
|
||||
```
|
||||
|
||||
Follow [Issue #65](https://github.com/facebook/react/issues/65) for discussion on this behavior.
|
||||
|
||||
|
||||
## HTML Entities
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ prev: jsx-gotchas.html
|
||||
next: multiple-components.html
|
||||
---
|
||||
|
||||
You've already [learned how to display data](/react/docs/displaying-data.html) with React. Now let's look at how to make our UIs interactive.
|
||||
You've already [learned how to display data](./displaying-data.html) with React. Now let's look at how to make our UIs interactive.
|
||||
|
||||
|
||||
## A Simple Example
|
||||
|
||||
@@ -73,7 +73,7 @@ When you create a React component instance, you can include additional React com
|
||||
<Parent><Child /></Parent>
|
||||
```
|
||||
|
||||
`Parent` can read its children by accessing the special `this.props.children` prop. **`this.props.children` is an opaque data structure:** use the [React.Children utilities](/react/docs/top-level-api.html#react.children) to manipulate them.
|
||||
`Parent` can read its children by accessing the special `this.props.children` prop.
|
||||
|
||||
|
||||
### Child Reconciliation
|
||||
@@ -124,7 +124,7 @@ The situation gets more complicated when the children are shuffled around (as in
|
||||
var results = this.props.results;
|
||||
return (
|
||||
<ol>
|
||||
{results.map(function(result) {
|
||||
{this.results.map(function(result) {
|
||||
return <li key={result.id}>{result.text}</li>;
|
||||
})}
|
||||
</ol>
|
||||
@@ -134,26 +134,6 @@ The situation gets more complicated when the children are shuffled around (as in
|
||||
|
||||
When React reconciles the keyed children, it will ensure that any child with `key` will be reordered (instead of clobbered) or destroyed (instead of reused).
|
||||
|
||||
You can also key children by passing an object. The object keys will be used as `key` for each value. However it is important to remember that JavaScript does not guarantee the ordering of properties will be preserved. In practice browsers will preserve property order **except** for properties that can be parsed as a 32-bit unsigned integers. Numeric properties will be ordered sequentially and before other properties. If this happens React will render components out of order. This can be avoided by adding a string prefix to the key:
|
||||
|
||||
```javascript
|
||||
render: function() {
|
||||
var items = {};
|
||||
|
||||
this.props.results.forEach(function(result) {
|
||||
// If result.id can look like a number (consider short hashes), then
|
||||
// object iteration order is not guaranteed. In this case, we add a prefix
|
||||
// to ensure the keys are strings.
|
||||
items['result-' + result.id] = <li>{result.text}</li>;
|
||||
});
|
||||
|
||||
return (
|
||||
<ol>
|
||||
{items}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Data Flow
|
||||
|
||||
@@ -164,7 +144,7 @@ In React, data flows from owner to owned component through `props` as discussed
|
||||
|
||||
You may be thinking that it's expensive to react to changing data if there are a large number of nodes under an owner. The good news is that JavaScript is fast and `render()` methods tend to be quite simple, so in most applications this is extremely fast. Additionally, the bottleneck is almost always the DOM mutation and not JS execution and React will optimize this for you using batching and change detection.
|
||||
|
||||
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](/react/docs/component-specs.html) for more information.
|
||||
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](component-specs.html) for more information.
|
||||
|
||||
> Note:
|
||||
>
|
||||
|
||||
@@ -12,7 +12,7 @@ When designing interfaces, break down the common design elements (buttons, form
|
||||
|
||||
## Prop Validation
|
||||
|
||||
As your app grows it's helpful to ensure that your components are used correctly. We do this by allowing you to specify `propTypes`. `React.PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. Note that for performance reasons `propTypes` is only checked in development mode. Here is an example documenting the different validators provided:
|
||||
As your app grows it's helpful to ensure that your components are used correctly. We do this by allowing you to specify `propTypes`. `React.PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. When an invalid value is provided for a prop, an error will be thrown. Here is an example documenting the different validators provided:
|
||||
|
||||
```javascript
|
||||
React.createClass({
|
||||
@@ -26,47 +26,22 @@ React.createClass({
|
||||
optionalObject: React.PropTypes.object,
|
||||
optionalString: React.PropTypes.string,
|
||||
|
||||
// Anything that can be rendered: numbers, strings, components or an array
|
||||
// containing these types.
|
||||
optionalRenderable: React.PropTypes.renderable,
|
||||
|
||||
// A React component.
|
||||
optionalComponent: React.PropTypes.component,
|
||||
|
||||
// You can ensure that your prop is limited to specific values by treating
|
||||
// it as an enum.
|
||||
optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
|
||||
|
||||
// An object that could be one of many types
|
||||
optionalUnion: React.PropTypes.oneOfType([
|
||||
React.PropTypes.string,
|
||||
React.PropTypes.number
|
||||
]),
|
||||
|
||||
// An array of a certain type
|
||||
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
|
||||
|
||||
// An object taking on a particular shape
|
||||
optionalObjectWithShape: React.PropTypes.shape({
|
||||
color: React.PropTypes.string,
|
||||
fontSize: React.PropTypes.number
|
||||
}),
|
||||
optionalEnum: React.PropTypes.oneOf(['News','Photos']),
|
||||
|
||||
// You can also declare that a prop is an instance of a class. This uses
|
||||
// JS's instanceof operator.
|
||||
someClass: React.PropTypes.instanceOf(SomeClass),
|
||||
|
||||
// You can chain any of the above with isRequired to make sure a warning is
|
||||
// shown if the prop isn't provided.
|
||||
requiredFunc: React.PropTypes.func.isRequired,
|
||||
|
||||
// An object of any kind
|
||||
requiredAny: React.PropTypes.any.isRequired,
|
||||
// You can chain any of the above with isRequired to make sure an error is
|
||||
// thrown if the prop isn't provided.
|
||||
requiredFunc: React.PropTypes.func.isRequired
|
||||
|
||||
// You can also specify a custom validator.
|
||||
customProp: function(props, propName, componentName) {
|
||||
if (!/matchme/.test(props[propName])) {
|
||||
console.warn('Validation failed!');
|
||||
throw new Error('Validation failed!')
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -116,32 +91,12 @@ React.renderComponent(
|
||||
);
|
||||
```
|
||||
|
||||
## Single Child
|
||||
|
||||
With `React.PropTypes.component` you can specify that only a single child can be passed to
|
||||
a component as children.
|
||||
|
||||
```javascript
|
||||
var MyComponent = React.createClass({
|
||||
propTypes: {
|
||||
children: React.PropTypes.component.isRequired
|
||||
},
|
||||
|
||||
render: function() {
|
||||
return
|
||||
<div>
|
||||
{this.props.children} // This must be exactly one element or it will throw.
|
||||
</div>;
|
||||
}
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
## Mixins
|
||||
|
||||
Components are the best way to reuse code in React, but sometimes very different components may share some common functionality. These are sometimes called [cross-cutting concerns](http://en.wikipedia.org/wiki/Cross-cutting_concern). React provides `mixins` to solve this problem.
|
||||
|
||||
One common use case is a component wanting to update itself on a time interval. It's easy to use `setInterval()`, but it's important to cancel your interval when you don't need it anymore to save memory. React provides [lifecycle methods](/react/docs/working-with-the-browser.html#component-lifecycle) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed.
|
||||
One common use case is a component wanting to update itself on a time interval. It's easy to use `setInterval()`, but it's important to cancel your interval when you don't need it anymore to save memory. React provides [lifecycle methods](./working-with-the-browser.html) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed.
|
||||
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
|
||||
@@ -87,7 +87,7 @@ If you want to initialize the component with a non-empty value, you can supply a
|
||||
|
||||
This example will function much like the **Controlled Components** example above.
|
||||
|
||||
Likewise, `<input>` supports `defaultChecked` and `<select>` supports `defaultValue`.
|
||||
Likewise, `<input>` supports `defaultChecked` and `<option>` supports `defaultSelected`.
|
||||
|
||||
|
||||
## Advanced Topics
|
||||
|
||||
@@ -10,7 +10,7 @@ next: more-about-refs.html
|
||||
React provides powerful abstractions that free you from touching the DOM directly in most cases, but sometimes you simply need to access the underlying API, perhaps to work with a third-party library or existing code.
|
||||
|
||||
|
||||
## The Virtual DOM
|
||||
## The Mock DOM
|
||||
|
||||
React is so fast because it never talks to the DOM directly. React maintains a fast in-memory representation of the DOM. `render()` methods return a *description* of the DOM, and React can diff this description with the in-memory representation to compute the fastest way to update the browser.
|
||||
|
||||
@@ -62,7 +62,7 @@ React.renderComponent(
|
||||
|
||||
## More About Refs
|
||||
|
||||
To learn more about refs, including ways to use them effectively, see our [more about refs](/react/docs/more-about-refs.html) documentation.
|
||||
To learn more about refs, including ways to use them effectively, see our [more about refs](./more-about-refs.html) documentation.
|
||||
|
||||
|
||||
## Component Lifecycle
|
||||
@@ -80,7 +80,7 @@ React provides lifecycle methods that you can specify to hook into this process.
|
||||
|
||||
* `getInitialState(): object` is invoked before a component is mounted. Stateful components should implement this and return the initial state data.
|
||||
* `componentWillMount()` is invoked immediately before mounting occurs.
|
||||
* `componentDidMount()` is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here.
|
||||
* `componentDidMount(DOMElement rootNode)` is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here.
|
||||
|
||||
|
||||
### Updating
|
||||
@@ -88,7 +88,7 @@ React provides lifecycle methods that you can specify to hook into this process.
|
||||
* `componentWillReceiveProps(object nextProps)` is invoked when a mounted component receives new props. This method should be used to compare `this.props` and `nextProps` to perform state transitions using `this.setState()`.
|
||||
* `shouldComponentUpdate(object nextProps, object nextState): boolean` is invoked when a component decides whether any changes warrant an update to the DOM. Implement this as an optimization to compare `this.props` with `nextProps` and `this.state` with `nextState` and return false if React should skip updating.
|
||||
* `componentWillUpdate(object nextProps, object nextState)` is invoked immediately before updating occurs. You cannot call `this.setState()` here.
|
||||
* `componentDidUpdate(object prevProps, object prevState)` is invoked immediately after updating occurs.
|
||||
* `componentDidUpdate(object prevProps, object prevState, DOMElement rootNode)` is invoked immediately after updating occurs.
|
||||
|
||||
|
||||
### Unmounting
|
||||
@@ -103,6 +103,12 @@ _Mounted_ composite components also support the following methods:
|
||||
* `getDOMNode(): DOMElement` can be invoked on any mounted component in order to obtain a reference to its rendered DOM node.
|
||||
* `forceUpdate()` can be invoked on any mounted component when you know that some deeper aspect of the component's state has changed without using `this.setState()`.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> The `DOMElement rootNode` argument of `componentDidMount()` and
|
||||
> `componentDidUpdate()` is a convenience. The same node can be obtained by
|
||||
> calling `this.getDOMNode()`.
|
||||
|
||||
|
||||
## Browser Support and Polyfills
|
||||
|
||||
@@ -113,7 +119,7 @@ In addition to that philosophy, we've also taken the stance that we, as authors
|
||||
|
||||
### Polyfills Needed to Support Older Browsers
|
||||
|
||||
`es5-shim.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim) provides the following that React needs:
|
||||
These six functions can be polyfilled using `es5-shim.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim):
|
||||
|
||||
* `Array.isArray`
|
||||
* `Array.prototype.forEach`
|
||||
@@ -121,25 +127,8 @@ In addition to that philosophy, we've also taken the stance that we, as authors
|
||||
* `Array.prototype.some`
|
||||
* `Date.now`
|
||||
* `Function.prototype.bind`
|
||||
* `Object.keys`
|
||||
|
||||
`es5-sham.js`, also from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim), provides the following that React needs:
|
||||
Other required polyfills:
|
||||
|
||||
* `Object.create`
|
||||
|
||||
The unminified build of React needs the following from [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).
|
||||
|
||||
* `console.*`
|
||||
|
||||
|
||||
### Cross-browser Issues
|
||||
|
||||
Although React is pretty good at abstracting browser differences, some browsers are limited or present quirky behaviors that we couldn't find a workaround.
|
||||
|
||||
|
||||
#### onScroll event on IE8
|
||||
|
||||
On IE8 the `onScroll` event doesn't bubble and IE8 doesn't have an API to define handlers to the capturing phase of an event, meaning there is no way for React to listen to these events.
|
||||
Currently a handler to this event is ignored on IE8.
|
||||
|
||||
See the [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) GitHub issue for more information.
|
||||
* `Object.create` – Provided by `es5-sham.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim).
|
||||
* `console.*` – Only needed when using the unminified build. If you need to polyfill this, try [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).
|
||||
|
||||
@@ -42,8 +42,7 @@ The open-source community has built tools that integrate JSX with several build
|
||||
|
||||
* [reactify](https://github.com/andreypopp/reactify) - use JSX with [browserify](http://browserify.org/)
|
||||
* [grunt-react](https://github.com/ericclemmons/grunt-react) - [grunt](http://gruntjs.com/) task for JSX
|
||||
* [gulp-react](https://github.com/sindresorhus/gulp-react) - [gulp](http://gulpjs.com/) task for JSX
|
||||
* [jsx-requirejs-plugin](https://github.com/philix/jsx-requirejs-plugin) - use JSX with [require.js](http://requirejs.org/) and precompile JSX files with r.js
|
||||
* [require-jsx](https://github.com/seiffert/require-jsx) - use JSX with [require.js](http://requirejs.org/)
|
||||
* [pyReact](https://github.com/facebook/react-python) - use JSX with [Python](http://www.python.org/)
|
||||
* [react-rails](https://github.com/facebook/react-rails) - use JSX with [Ruby on Rails](http://rubyonrails.org/)
|
||||
|
||||
@@ -55,3 +54,7 @@ The open-source community has built tools that integrate JSX with several build
|
||||
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.
|
||||
|
||||
@@ -9,9 +9,8 @@ next: animation.html
|
||||
|
||||
`React.addons` is where we park some useful utilities for building React apps. **These should be considered experimental** but will eventually be rolled into core or a blessed utilities library:
|
||||
|
||||
- [`ReactTransitions`](animation.html), for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal.
|
||||
- [`ReactLink`](two-way-binding-helpers.html), to simplify the coordination between user's form input data and and the component's state.
|
||||
- [`classSet`](class-name-manipulation.html), for manipulating the DOM `class` string a bit more cleanly.
|
||||
- [`ReactTestUtils`](test-utils.html), simple helpers for writing test cases (unminified build only).
|
||||
- `ReactTransitions`, for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal.
|
||||
- `ReactLink`, to simplify the coordination between user's form input data and and the component's state.
|
||||
- `classSet`, for manipulating the DOM `class` string a bit more cleanly.
|
||||
|
||||
To get the add-ons, use `react-with-addons.js` (and its minified counterpart) rather than the common `react.js`.
|
||||
|
||||
@@ -7,20 +7,16 @@ prev: addons.html
|
||||
next: two-way-binding-helpers.html
|
||||
---
|
||||
|
||||
React provides a `ReactTransitionGroup` addon component as a low-level API for animation, and a `ReactCSSTransitionGroup` for easily implementing basic CSS animations and transitions.
|
||||
`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.
|
||||
|
||||
## High-level API: `ReactCSSTransitionGroup`
|
||||
## Getting Started
|
||||
|
||||
`ReactCSSTransitionGroup` is based on `ReactTransitionGroup` and 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
|
||||
|
||||
`ReactCSSTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out.
|
||||
`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 ReactCSSTransitionGroup = React.addons.TransitionGroup;
|
||||
var ReactTransitionGroup = React.addons.TransitionGroup;
|
||||
|
||||
var TodoList = React.createClass({
|
||||
getInitialState: function() {
|
||||
@@ -39,7 +35,7 @@ var TodoList = React.createClass({
|
||||
render: function() {
|
||||
var items = this.state.items.map(function(item, i) {
|
||||
return (
|
||||
<div key={item} onClick={this.handleRemove.bind(this, i)}>
|
||||
<div key={i} onClick={this.handleRemove.bind(this, i)}>
|
||||
{item}
|
||||
</div>
|
||||
);
|
||||
@@ -47,16 +43,16 @@ var TodoList = React.createClass({
|
||||
return (
|
||||
<div>
|
||||
<div><button onClick={this.handleAdd} /></div>
|
||||
<ReactCSSTransitionGroup transitionName="example">
|
||||
<ReactTransitionGroup transitionName="example">
|
||||
{items}
|
||||
</ReactCSSTransitionGroup>
|
||||
</ReactTransitionGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
In this component, when a new item is added to `ReactCSSTransitionGroup` it will get the `example-enter` CSS class and the `example-enter-active` CSS class added in the next tick. This is a convention based on the `transitionName` prop.
|
||||
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:
|
||||
|
||||
@@ -71,7 +67,7 @@ You can use these classes to trigger a CSS animation or transition. For example,
|
||||
}
|
||||
```
|
||||
|
||||
You'll notice that when you try to remove an item `ReactCSSTransitionGroup` 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 `ReactCSSTransitionGroup` keeps your DOM elements on the page until the animation completes. Try adding this CSS:
|
||||
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 {
|
||||
@@ -84,36 +80,18 @@ You'll notice that when you try to remove an item `ReactCSSTransitionGroup` keep
|
||||
}
|
||||
```
|
||||
|
||||
### Disabling Animations
|
||||
## Disabling Animations
|
||||
|
||||
You can disable animating `enter` or `leave` animations if you want. For example, sometimes you may want an `enter` animation and no `leave` animation, but `ReactCSSTransitionGroup` waits for an animation to complete before removing your DOM node. You can add `transitionEnter={false}` or `transitionLeave={false}` props to `ReactCSSTransitionGroup` to disable these animations.
|
||||
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.
|
||||
|
||||
## Low-level API: `ReactTransitionGroup`
|
||||
|
||||
`ReactTransitionGroup` is the basis for animations. When children are declaratively added or removed from it (as in the example above) special lifecycle hooks are called on them.
|
||||
|
||||
### `componentWillEnter(callback)`
|
||||
|
||||
This is called at the same time as `componentDidMount()` for components added to an existing `TransitionGroup`. It will block other animations from occurring until `callback` is called. It will not be called on the initial render of a `TransitionGroup`.
|
||||
|
||||
### `componentDidEnter()`
|
||||
|
||||
This is called after the `callback` function that was passed to `componentWillEnter` is called.
|
||||
|
||||
### `componentWillLeave(callback)`
|
||||
|
||||
This is called when the child has been removed from the `ReactTransitionGroup`. Though the child has been removed, `ReactTransitionGroup` will keep it in the DOM until `callback` is called.
|
||||
|
||||
### `componentDidLeave()`
|
||||
|
||||
This is called when the `willLeave` `callback` is called (at the same time as `componentWillUnmount`).
|
||||
|
||||
### Rendering a Different Component
|
||||
## 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{1}
|
||||
<ReactTransitionGroup component={React.DOM.ul}>
|
||||
```javascript{3}
|
||||
<ReactTransitionGroup
|
||||
transitionName="example"
|
||||
component={React.DOM.ul}>
|
||||
...
|
||||
</ReactTransitionGroup>
|
||||
```
|
||||
|
||||
@@ -17,7 +17,7 @@ In React, data flows one way: from owner to child. This is because data only flo
|
||||
|
||||
However, there are lots of applications that require you to read some data and flow it back into your program. For example, when developing forms, you'll often want to update some React `state` when you receive user input. Or perhaps you want to perform layout in JavaScript and react to changes in some DOM element size.
|
||||
|
||||
In React, you would implement this by listening to a "change" event, read from your data source (usually the DOM) and call `setState()` on one of your components. "Closing the data flow loop" explicitly leads to more understandable and easier-to-maintain programs. See [our forms documentation](/react/docs/forms.html) for more information.
|
||||
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`.
|
||||
|
||||
@@ -62,12 +62,10 @@ var WithLink = React.createClass({
|
||||
});
|
||||
```
|
||||
|
||||
`LinkedStateMixin` adds a method to your React component called `linkState()`. `linkState()` returns a `ReactLink` object which contains the current value of the React state and a callback to change it.
|
||||
`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.
|
||||
|
||||
Note that `<input>` supports ReactLink for both `value` and `checked`.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -4,7 +4,7 @@ title: Class Name Manipulation
|
||||
layout: docs
|
||||
permalink: class-name-manipulation.html
|
||||
prev: two-way-binding-helpers.html
|
||||
next: test-utils.html
|
||||
next: examples.html
|
||||
---
|
||||
|
||||
`classSet()` is a neat utility for easily manipulating the DOM `class` string.
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
---
|
||||
id: test-utils
|
||||
title: Test Utilities
|
||||
layout: docs
|
||||
permalink: test-utils.html
|
||||
prev: class-name-manipulation.html
|
||||
next: clone-with-props.html
|
||||
---
|
||||
|
||||
`React.addons.TestUtils` makes it easy to test React components in the testing framework of your choice (we use [Jasmine](http://pivotal.github.io/jasmine/) with [jsdom](https://github.com/tmpvar/jsdom)).
|
||||
|
||||
### Simulate
|
||||
|
||||
```javascript
|
||||
Simulate.{eventName}({ReactComponent|DOMElement} element, object eventData)
|
||||
```
|
||||
|
||||
Simulate an event dispatch on a React component instance or browser DOM node with optional `eventData` event data. **This is possibly the single most useful utility in `ReactTestUtils`.**
|
||||
|
||||
Example usage:
|
||||
|
||||
```javascript
|
||||
React.addons.TestUtils.Simulate.click(myComponent);
|
||||
React.addons.TestUtils.Simulate.change(myComponent);
|
||||
React.addons.TestUtils.Simulate.keydown(myComponent, {key: "Enter"});
|
||||
```
|
||||
|
||||
`Simulate` has a method for every event that React understands.
|
||||
|
||||
### renderIntoDocument
|
||||
|
||||
```javascript
|
||||
ReactComponent renderIntoDocument(ReactComponent instance)
|
||||
```
|
||||
|
||||
Render a component into a detached DOM node in the document. **This function requires a DOM.**
|
||||
|
||||
### mockComponent
|
||||
|
||||
```javascript
|
||||
object mockComponent(function componentClass, string? tagName)
|
||||
```
|
||||
|
||||
Pass a mocked component module to this method to augment it with useful methods that allow it to be used as a dummy React component. Instead of rendering as usual, the component will become a simple `<div>` (or other tag if `mockTagName` is provided) containing any provided children.
|
||||
|
||||
### isComponentOfType
|
||||
|
||||
```javascript
|
||||
boolean isComponentOfType(ReactComponent instance, function componentClass)
|
||||
```
|
||||
|
||||
Returns true if `instance` is an instance of a React `componentClass`.
|
||||
|
||||
### isDOMComponent
|
||||
|
||||
```javascript
|
||||
boolean isDOMComponent(ReactComponent instance)
|
||||
```
|
||||
|
||||
Returns true if `instance` is a DOM component (such as a `<div>` or `<span>`).
|
||||
|
||||
### isCompositeComponent
|
||||
|
||||
```javascript
|
||||
boolean isCompositeComponent(ReactComponent instance)`
|
||||
```
|
||||
|
||||
Returns true if `instance` is a composite component (created with `React.createClass()`)
|
||||
|
||||
### isCompositeComponentWithType
|
||||
|
||||
```javascript
|
||||
boolean isCompositeComponentWithType(ReactComponent instance, function componentClass)
|
||||
```
|
||||
|
||||
The combination of `isComponentOfType()` and `isCompositeComponent()`.
|
||||
|
||||
### isTextComponent
|
||||
|
||||
```javascript
|
||||
boolean isTextComponent(ReactComponent instance)
|
||||
```
|
||||
|
||||
Returns true if `instance` is a plain text component.
|
||||
|
||||
### findAllInRenderedTree
|
||||
|
||||
```javascript
|
||||
array findAllInRenderedTree(ReactComponent tree, function test)
|
||||
```
|
||||
|
||||
Traverse all components in `tree` and accumulate all components where `test(component)` is true. This is not that useful on its own, but it's used as a primitive for other test utils.
|
||||
|
||||
### scryRenderedDOMComponentsWithClass
|
||||
|
||||
```javascript
|
||||
array scryRenderedDOMComponentsWithClass(ReactCompoennt tree, string className)
|
||||
```
|
||||
|
||||
Finds all instance of components in the rendered tree that are DOM components with the class name matching `className`.
|
||||
|
||||
### findRenderedDOMComponentWithClass
|
||||
|
||||
```javascript
|
||||
ReactComponent findRenderedDOMComponentWithClass(ReactComponent tree, string className)
|
||||
```
|
||||
|
||||
Like `scryRenderedDOMComponentsWithClass()` but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
|
||||
|
||||
### scryRenderedDOMComponentsWithTag
|
||||
|
||||
```javascript
|
||||
array scryRenderedDOMComponentsWithTag(ReactComponent tree, string tagName)
|
||||
```
|
||||
|
||||
Finds all instance of components in the rendered tree that are DOM components with the tag name matching `tagName`.
|
||||
|
||||
### findRenderedDOMComponentWithTag
|
||||
|
||||
```javascript
|
||||
ReactComponent findRenderedDOMComponentWithTag(ReactComponent tree, string tagName)
|
||||
```
|
||||
|
||||
Like `scryRenderedDOMComponentsWithTag()` but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
|
||||
|
||||
### scryRenderedComponentsWithType
|
||||
|
||||
```javascript
|
||||
array scryRenderedComponentsWithType(ReactComponent tree, function componentClass)
|
||||
```
|
||||
|
||||
Finds all instances of components with type equal to `componentClass`.
|
||||
|
||||
### findRenderedComponentWithType
|
||||
|
||||
```javascript
|
||||
ReactComponent findRenderedComponentWithType(ReactComponent tree, function componentClass)
|
||||
```
|
||||
|
||||
Same as `scryRenderedComponentsWithType()` but expects there to be one result and returns that one result, or throws exception if there is any other number of matches besides one.
|
||||
@@ -1,14 +0,0 @@
|
||||
---
|
||||
id: clone-with-props
|
||||
title: Cloning Components
|
||||
layout: docs
|
||||
permalink: clone-with-props.html
|
||||
prev: test-utils.html
|
||||
next: examples.html
|
||||
---
|
||||
|
||||
In rare situations a component may want to change the props of a component that it doesn't own (like changing the `className` of a component passed as `this.props.children`). Other times it may want to make multiple copies of a component passed to it. `cloneWithProps()` makes this possible.
|
||||
|
||||
#### `ReactComponent React.addons.cloneWithProps(ReactComponent component, object? extraProps)`
|
||||
|
||||
Do a shallow copy of `component` and merge any props provided by `extraProps`. Props are merged in the same manner as [`transferPropsTo()`](/react/docs/component-api.html#transferpropsto), so props like `className` will be merged intelligently.
|
||||
@@ -3,7 +3,7 @@ id: examples
|
||||
title: Examples
|
||||
layout: docs
|
||||
permalink: examples.html
|
||||
prev: class-name-manipulation.html
|
||||
prev: addons.html
|
||||
---
|
||||
|
||||
### Production Apps
|
||||
@@ -15,7 +15,8 @@ prev: class-name-manipulation.html
|
||||
|
||||
### Sample Code
|
||||
|
||||
* We've included [a step-by-step comment box tutorial](/react/docs/tutorial.html).
|
||||
* We've included [a step-by-step comment box tutorial](./tutorial.html).
|
||||
* [The React starter kit](/react/downloads.html) includes several examples which you can [view online in our GitHub repository](https://github.com/facebook/react/tree/master/examples/).
|
||||
* [React Page](https://github.com/facebook/react-page) is a simple React project creator to get you up-and-running quickly with React. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
|
||||
* [React one-hour email](https://github.com/petehunt/react-one-hour-email/commits/master) goes step-by-step from a static HTML mock to an interactive email reader (written in just one hour!)
|
||||
* [Rendr + React app template](https://github.com/petehunt/rendr-react-template/) demonstrates how to use React's server rendering capabilities.
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
---
|
||||
id: complementary-tools
|
||||
title: Complementary Tools
|
||||
layout: docs
|
||||
permalink: complementary-tools.html
|
||||
prev: videos.html
|
||||
next: example-apps.html
|
||||
---
|
||||
|
||||
React is a small library that does one thing well. Here's a list of tools we've found that work really well with React when building applications.
|
||||
|
||||
If you want your project on this list, or think one of these projects should be removed, [open an issue on GitHub](https://github.com/facebook/react/issues/new).
|
||||
|
||||
### JSX integrations
|
||||
|
||||
* **[jsxhint](https://npmjs.org/package/jsxhint)** [JSHint](http://jshint.com/) (linting) support
|
||||
* **[reactify](https://npmjs.org/package/reactify)** [Browserify](http://browserify.org/) transform
|
||||
* **[node-jsx](https://npmjs.org/package/node-jsx)** Native [Node](http://nodejs.org/) support
|
||||
* **[jsx-loader](https://npmjs.org/package/jsx-loader)** Loader for [webpack](http://webpack.github.io/)
|
||||
* **[grunt-react](https://npmjs.org/package/grunt-react)** [GruntJS](http://gruntjs.com/) task
|
||||
* **[gulp-react](https://npmjs.org/package/gulp-react)** [GulpJS](http://gulpjs.com/) plugin
|
||||
* **[jsx-requirejs-plugin](https://github.com/philix/jsx-requirejs-plugin)** [RequireJS](http://requirejs.org/) plugin
|
||||
* **[react-meteor](https://github.com/benjamn/react-meteor)** [Meteor](http://www.meteor.com/) plugin
|
||||
|
||||
### Full-stack starter kits
|
||||
|
||||
* **[react-quickstart](https://github.com/andreypopp/react-quickstart)** Quick-start template for `express`, `browserify`, `react-router-component` and `react-async` (**includes "isomorphic" server rendering**)
|
||||
* **[generator-react-webpack](https://github.com/newtriks/generator-react-webpack)** [Yeoman](http://yeoman.io/) generator for React and Webpack
|
||||
* **[Genesis Skeleton](http://genesis-skeleton.com/)** Modern, opinionated, full-stack starter kit for rapid, streamlined application development (supports React)
|
||||
* **[react-starter-template](https://github.com/johnthethird/react-starter-template)** Starter template with Gulp, Webpack and Bootstrap
|
||||
* **[react-brunch](https://npmjs.org/package/react-brunch)** [Brunch](http://brunch.io/) plugin
|
||||
* **[react-browserify-template](https://github.com/petehunt/react-browserify-template)** Quick-start with Browserify
|
||||
|
||||
### Routing
|
||||
|
||||
* **[director](https://github.com/flatiron/director)** (for an example see [TodoMVC](https://github.com/tastejs/todomvc/blob/gh-pages/architecture-examples/react/js/app.jsx#L29))
|
||||
* **[Backbone](http://backbonejs.org/)** (for an example see [github-issues-viewer](https://github.com/jaredly/github-issues-viewer))
|
||||
* **[react-router](https://github.com/jaredly/react-router)** (example coming soon)
|
||||
* **[react-router-component](https://github.com/andreypopp/react-router-component)**
|
||||
|
||||
### Model management
|
||||
|
||||
* **[react.backbone](https://github.com/usepropeller/react.backbone)** Use [Backbone](http://backbonejs.org) models with React
|
||||
* **[cortex](https://github.com/mquan/cortex/)** A JavaScript library for centrally managing data with React
|
||||
* **[avers](https://github.com/wereHamster/avers)** A modern client-side model abstraction library
|
||||
|
||||
### Data fetching
|
||||
|
||||
* **[react-async](https://github.com/andreypopp/react-async)** Adds a `getInitialStateAsync(cb)` method suitable for data fetching on both the client and the server.
|
||||
* **[superagent](http://visionmedia.github.io/superagent/)** A lightweight "isomorphic" library for AJAX requests.
|
||||
|
||||
### UI components
|
||||
|
||||
* **[react-bootstrap](https://github.com/stevoland/react-bootstrap)** Bootstrap 3 components built with React
|
||||
* **[react-topcoat](https://github.com/plaxdan/react-topcoat)** Topcoat components built with React
|
||||
* **[react-lorem-component](https://github.com/martinandert/react-lorem-component)** Lorem Ipsum placeholder component
|
||||
* **[wingspan-forms](https://github.com/wingspan/wingspan-forms)** React library for dynamic forms & grids; widgets provided by KendoUI
|
||||
@@ -1,14 +0,0 @@
|
||||
---
|
||||
id: example-apps
|
||||
title: Example apps
|
||||
layout: docs
|
||||
permalink: example-apps.html
|
||||
prev: complementary-tools.html
|
||||
---
|
||||
|
||||
Here is a selection of open-source apps built with React.
|
||||
|
||||
* **[TodoMVC](https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/react/js)**
|
||||
* **[Khan Academy question editor](https://github.com/khan/perseus)** (browse their GitHub account for many more production apps!)
|
||||
* **[github-issues-viewer](https://github.com/jaredly/github-issues-viewer)**
|
||||
* **[hn-react](https://github.com/prabirshrestha/hn-react)** Dead-simple Hacker News client in React
|
||||
@@ -28,7 +28,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="build/react.js"></script>
|
||||
<script src="build/react.min.js"></script>
|
||||
<script src="build/JSXTransformer.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
@@ -44,7 +44,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
|
||||
</html>
|
||||
```
|
||||
|
||||
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](/react/docs/jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
|
||||
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
|
||||
|
||||
### Separate File
|
||||
|
||||
@@ -90,7 +90,7 @@ React.renderComponent(
|
||||
|
||||
> Note:
|
||||
>
|
||||
> The comment parser is very strict right now; in order for it to pick up the `@jsx` modifier, two conditions are required. The `@jsx` comment block must be the first comment on the file. The comment must start with `/**` (`/*` and `//` will not work). If the parser can't find the `@jsx` comment, it will output the file without transforming it.
|
||||
> The comment parser is very strict right now, in order for it to pick up the `@jsx` modifier, two conditions are required. The `@jsx` comment block must be the first comment on the file. The comment must start with `/**` (`/*` and `//` will not work). If the parser can't find the `@jsx` comment, it will output the file without transforming it.
|
||||
|
||||
Update your HTML file as below:
|
||||
|
||||
@@ -99,7 +99,7 @@ Update your HTML file as below:
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello React!</title>
|
||||
<script src="build/react.js"></script>
|
||||
<script src="build/react.min.js"></script>
|
||||
<!-- No need for JSXTransformer! -->
|
||||
</head>
|
||||
<body>
|
||||
@@ -115,4 +115,4 @@ If you want to use React within a module system, [fork our repo](http://github.c
|
||||
|
||||
## Next Steps
|
||||
|
||||
Check out [the tutorial](/react/docs/tutorial.html) and the other examples in the `/examples` directory to learn more. Good luck, and welcome!
|
||||
Check out [the tutorial](tutorial.html) and the other examples in the `/examples` directory to learn more. Good luck, and welcome!
|
||||
|
||||
@@ -11,35 +11,6 @@ next: component-api.html
|
||||
`React` is the entry point to the React framework. If you're using one of the prebuilt packages it's available as a global; if you're using CommonJS modules you can `require()` it.
|
||||
|
||||
|
||||
### React.Children
|
||||
|
||||
`React.Children` provides utilities for dealing with the `this.props.children` opaque data structure.
|
||||
|
||||
#### React.Children.map
|
||||
|
||||
```javascript
|
||||
object React.Children.map(object children, function fn [, object context])
|
||||
```
|
||||
|
||||
Invoke `fn` on every immediate child contained within `children` with `this` set to `context`. If `children` is a nested object or array it will be traversed: `fn` will never be passed the container objects. If children is `null` or `undefined` returns `null` or `undefined` rather than an empty object.
|
||||
|
||||
#### React.Children.forEach
|
||||
|
||||
```javascript
|
||||
React.Children.forEach(object children, function fn [, object context])
|
||||
```
|
||||
|
||||
Like `React.Children.map()` but does not return an object.
|
||||
|
||||
#### React.Children.only
|
||||
|
||||
```javascript
|
||||
object React.Children.only(object children)
|
||||
```
|
||||
|
||||
Return the only child in `children`. Throws otherwise.
|
||||
|
||||
|
||||
### React.DOM
|
||||
|
||||
`React.DOM` provides all of the standard HTML tags needed to build a React app. You generally don't use it directly; instead, just include it as part of the `/** @jsx React.DOM */` docblock.
|
||||
@@ -60,9 +31,9 @@ Configure React's event system to handle touch events on mobile devices.
|
||||
function createClass(object specification)
|
||||
```
|
||||
|
||||
Create a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
|
||||
Creates a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
|
||||
|
||||
For more information about the specification object, see [Component Specs and Lifecycle](/react/docs/component-specs.html).
|
||||
For more information about the specification object, see [Component Specs and Lifecycle](component-specs.html).
|
||||
|
||||
|
||||
### React.renderComponent
|
||||
@@ -75,7 +46,7 @@ ReactComponent renderComponent(
|
||||
)
|
||||
```
|
||||
|
||||
Render a React component into the DOM in the supplied `container` and return a reference to the component.
|
||||
Renders a React component into the DOM in the supplied `container`.
|
||||
|
||||
If the React component was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
|
||||
|
||||
@@ -85,10 +56,10 @@ If the optional callback is provided, it will be executed after the component is
|
||||
### React.unmountComponentAtNode
|
||||
|
||||
```javascript
|
||||
boolean unmountComponentAtNode(DOMElement container)
|
||||
unmountComponentAtNode(DOMElement container)
|
||||
```
|
||||
|
||||
Remove a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns `true` if a component was unmounted and `false` if there was no component to unmount.
|
||||
Remove a mounted React component from the DOM and clean up its event handlers and state.
|
||||
|
||||
> Note:
|
||||
>
|
||||
@@ -98,9 +69,9 @@ Remove a mounted React component from the DOM and clean up its event handlers an
|
||||
### React.renderComponentToString
|
||||
|
||||
```javascript
|
||||
string renderComponentToString(ReactComponent component)
|
||||
renderComponentToString(ReactComponent component, function callback)
|
||||
```
|
||||
|
||||
Render a component to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
|
||||
Render a component to its initial HTML. This should only be used on the server. React will call `callback` with an HTML string when the markup is ready. You can use this method to can generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
|
||||
|
||||
If you call `React.renderComponent()` on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
|
||||
|
||||
@@ -9,7 +9,7 @@ next: component-specs.html
|
||||
|
||||
## ReactComponent
|
||||
|
||||
Component classes created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
|
||||
Component classses created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
|
||||
|
||||
|
||||
### getDOMNode
|
||||
@@ -107,12 +107,3 @@ If your `render()` method reads from something other than `this.props` or `this.
|
||||
Calling `forceUpdate()` will cause `render()` to be called on the component and its children, but React will still only update the DOM if the markup changes.
|
||||
|
||||
Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your application much simpler and more efficient.
|
||||
|
||||
|
||||
### isMounted()
|
||||
|
||||
```javascript
|
||||
bool isMounted()
|
||||
```
|
||||
|
||||
`isMounted()` returns true if the component is rendered into the DOM, false otherwise. You can use this method to guard asynchronous calls to `setState()` or `forceUpdate()`.
|
||||
|
||||
@@ -20,7 +20,7 @@ ReactComponent render()
|
||||
|
||||
The `render()` method is required.
|
||||
|
||||
When called, it should examine `this.props` and `this.state` and return a single child component. This child component can be either a virtual representation of a native DOM component (such as `<div />` or `React.DOM.div()`) or another composite component that you've defined yourself.
|
||||
When called, it should examine `this.props` and `this.state` and return a single child component. This child component can be either a native DOM component (such as `<div>`) or another composite component that you've defined yourself.
|
||||
|
||||
The `render()` function should be *pure*, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using `setTimeout`). If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes server rendering more practical and makes components easier to think about.
|
||||
|
||||
@@ -51,7 +51,7 @@ This method is invoked before `getInitialState` and therefore cannot rely on `th
|
||||
object propTypes
|
||||
```
|
||||
|
||||
The `propTypes` object allows you to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html).
|
||||
The `propTypes` object allows you to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](reusable-components.html).
|
||||
|
||||
<!-- TODO: Document propTypes here directly. -->
|
||||
|
||||
@@ -62,45 +62,11 @@ The `propTypes` object allows you to validate props being passed to your compone
|
||||
array mixins
|
||||
```
|
||||
|
||||
The `mixins` array allows you to use mixins to share behavior among multiple components. For more information about mixins, see [Reusable Components](/react/docs/reusable-components.html).
|
||||
The `mixins` array allows you to use mixins to share behavior among multiple components. For more information about mixins, see [Reusable Components](reusable-components.html).
|
||||
|
||||
<!-- TODO: Document mixins here directly. -->
|
||||
|
||||
|
||||
### statics
|
||||
|
||||
```javascript
|
||||
object statics
|
||||
```
|
||||
|
||||
The `statics` object allows you to define static methods that can be called on the component class. For example:
|
||||
|
||||
```javascript
|
||||
var MyComponent = React.createClass({
|
||||
statics: {
|
||||
customMethod: function(foo) {
|
||||
return foo === 'bar';
|
||||
}
|
||||
},
|
||||
render: function() {
|
||||
}
|
||||
});
|
||||
|
||||
MyComponent.customMethod('bar'); // true
|
||||
```
|
||||
|
||||
Methods defined within this block are _static_, meaning that you can run them before any component instances are created, and the methods do not have access to the props or state of your components. If you want to check the value of props in a static method, have the caller pass in the props as an argument to the static method.
|
||||
|
||||
|
||||
### displayName
|
||||
|
||||
```javascript
|
||||
string displayName
|
||||
```
|
||||
|
||||
The `displayName` string is used in debugging messages. JSX sets this value automatically, see [JSX in Depth](/react/docs/jsx-in-depth.html#react-composite-components).
|
||||
|
||||
|
||||
## Lifecycle Methods
|
||||
|
||||
Various methods are executed at specific points in a component's lifecycle.
|
||||
@@ -112,23 +78,19 @@ Various methods are executed at specific points in a component's lifecycle.
|
||||
componentWillMount()
|
||||
```
|
||||
|
||||
Invoked once, immediately before the initial rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change.
|
||||
Invoked immediately before rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change.
|
||||
|
||||
|
||||
### Mounting: componentDidMount
|
||||
|
||||
```javascript
|
||||
componentDidMount()
|
||||
componentDidMount(DOMElement rootNode)
|
||||
```
|
||||
|
||||
Invoked immediately after rendering occurs. At this point in the lifecycle, the component has a DOM representation which you can access via `this.getDOMNode()`.
|
||||
Invoked immediately after rendering occurs. At this point in the lifecycle, the component has a DOM representation which you can access via the `rootNode` argument or by calling `this.getDOMNode()`.
|
||||
|
||||
If you want to integrate with other JavaScript frameworks, set timers using `setTimeout` or `setInterval`, or send AJAX requests, perform those operations in this method.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> Prior to v0.6, the DOM node was passed in as the last argument. If you were using this, you can still access the DOM node by calling `this.getDOMNode()`.
|
||||
|
||||
|
||||
### Updating: componentWillReceiveProps
|
||||
|
||||
@@ -195,17 +157,13 @@ Use this as an opportunity to perform preparation before an update occurs.
|
||||
### Updating: componentDidUpdate
|
||||
|
||||
```javascript
|
||||
componentDidUpdate(object prevProps, object prevState)
|
||||
componentDidUpdate(object prevProps, object prevState, DOMElement rootNode)
|
||||
```
|
||||
|
||||
Invoked immediately after updating occurs. This method is not called for the initial render.
|
||||
|
||||
Use this as an opportunity to operate on the DOM when the component has been updated.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> Prior to v0.6, the DOM node was passed in as the last argument. If you were using this, you can still access the DOM node by calling `this.getDOMNode()`.
|
||||
|
||||
|
||||
### Unmounting: componentWillUnmount
|
||||
|
||||
|
||||
@@ -11,32 +11,28 @@ next: events.html
|
||||
|
||||
React attempts to support all common elements. If you need an element that isn't listed here, please file an issue.
|
||||
|
||||
### HTML Elements
|
||||
The following elements are supported:
|
||||
|
||||
The following HTML elements are supported:
|
||||
|
||||
### HTML Elements
|
||||
|
||||
```
|
||||
a abbr address area article aside audio b base bdi bdo big blockquote body br
|
||||
button canvas caption cite code col colgroup data datalist dd del details dfn
|
||||
div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6
|
||||
head header hr html i iframe img input ins kbd keygen label legend li link
|
||||
main map mark menu menuitem meta meter nav noscript object ol optgroup option
|
||||
output p param pre progress q rp rt ruby s samp script section select small
|
||||
source span strong style sub summary sup table tbody td textarea tfoot th
|
||||
thead time title tr track u ul var video wbr
|
||||
head header hr html i iframe img input ins kbd keygen label legend li link main
|
||||
map mark menu menuitem meta meter nav noscript object ol optgroup option output
|
||||
p param pre progress q rp rt ruby s samp script section select small source
|
||||
span strong style sub summary sup table tbody td textarea tfoot th thead time
|
||||
title tr track u ul var video wbr
|
||||
```
|
||||
|
||||
### SVG elements
|
||||
|
||||
The following SVG elements are supported:
|
||||
|
||||
```
|
||||
circle defs g line linearGradient path polygon polyline radialGradient rect
|
||||
stop svg text
|
||||
circle g line path polyline rect svg text
|
||||
```
|
||||
|
||||
You may also be interested in [react-art](https://github.com/facebook/react-art), a drawing library for React that can render to Canvas, SVG, or VML (for IE8).
|
||||
|
||||
|
||||
## Supported Attributes
|
||||
|
||||
@@ -46,27 +42,22 @@ React supports all `data-*` and `aria-*` attributes as well as every attribute i
|
||||
>
|
||||
> All attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
|
||||
|
||||
For a list of events, see [Supported Events](/react/docs/events.html).
|
||||
For a list of events, see [Supported Events](events.html).
|
||||
|
||||
### HTML Attributes
|
||||
|
||||
These standard attributes are supported:
|
||||
|
||||
```
|
||||
accept accessKey action allowFullScreen allowTransparency alt async
|
||||
accept accessKey action allowFullScreen allowTransparency alt autoCapitalize
|
||||
autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked
|
||||
className colSpan cols content contentEditable contextMenu controls data
|
||||
dateTime defer dir disabled draggable encType form formNoValidate frameBorder
|
||||
height hidden href htmlFor httpEquiv icon id label lang list loop max
|
||||
maxLength method min multiple name noValidate pattern placeholder poster
|
||||
preload radioGroup readOnly rel required role rowSpan rows sandbox scope
|
||||
scrollLeft scrollTop seamless selected size span spellCheck src srcDoc step
|
||||
style tabIndex target title type value width wmode
|
||||
className colSpan content contentEditable contextMenu controls data dateTime
|
||||
dir disabled draggable encType form frameBorder height hidden href htmlFor
|
||||
httpEquiv icon id label lang list max maxLength method min multiple name
|
||||
pattern placeholder poster preload radioGroup readOnly rel required role
|
||||
rowSpan scrollLeft scrollTop selected size spellCheck src step style tabIndex
|
||||
target title type value width wmode
|
||||
```
|
||||
|
||||
In addition, the non-standard `autoCapitalize` and `autoCorrect` attributes are supported for Mobile Safari, and the `property` attribute is supported for Open Graph `<meta>` tags.
|
||||
|
||||
There is also the React-specific attribute `dangerouslySetInnerHTML` ([more here](/react/docs/special-non-dom-attributes.html)), used for directly inserting HTML strings into a component.
|
||||
In addition, the non-standard `autoCapitalize` attribute is supported for Mobile Safari.
|
||||
|
||||
### SVG Attributes
|
||||
|
||||
|
||||
@@ -62,16 +62,14 @@ Properties:
|
||||
|
||||
```javascript
|
||||
boolean altKey
|
||||
String char
|
||||
boolean ctrlKey
|
||||
Number charCode
|
||||
String key
|
||||
Number keyCode
|
||||
String locale
|
||||
Number location
|
||||
boolean metaKey
|
||||
boolean repeat
|
||||
boolean shiftKey
|
||||
Number which
|
||||
```
|
||||
|
||||
|
||||
@@ -98,7 +96,7 @@ Event names:
|
||||
onChange onInput onSubmit
|
||||
```
|
||||
|
||||
For more information about the onChange event, see [Forms](/react/docs/forms.html).
|
||||
For more information about the onChange event, see [Forms](forms.html).
|
||||
|
||||
|
||||
### Mouse Events
|
||||
@@ -108,7 +106,7 @@ Event names:
|
||||
```
|
||||
onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave
|
||||
onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
|
||||
onMouseMove onMouseOut onMouseOver onMouseUp
|
||||
onMouseMove onMouseUp
|
||||
```
|
||||
|
||||
Properties:
|
||||
|
||||
@@ -4,13 +4,11 @@ title: DOM Differences
|
||||
layout: docs
|
||||
permalink: dom-differences.html
|
||||
prev: events.html
|
||||
next: special-non-dom-attributes.html
|
||||
---
|
||||
|
||||
React has implemented a browser-independent events and DOM system for performance and cross-browser compatibility reasons. We took the opportunity to clean up a few rough edges in browser DOM implementations.
|
||||
|
||||
* All DOM properties and attributes (including event handlers) should be camelCased to be consistent with standard JavaScript style. We intentionally break with the spec here since the spec is inconsistent. **However**, `data-*` and `aria-*` attributes [conform to the specs](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#data-*) and should be lower-cased only.
|
||||
* All DOM properties and attributes (including event handlers) should be camelCased to be consistent with standard JavaScript style. We intentionally break with the spec here since the spec is inconsistent.
|
||||
* The `style` attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM `style` JavaScript property, is more efficient, and prevents XSS security holes.
|
||||
* All event objects conform to the W3C spec, and all events (including submit) bubble correctly per the W3C spec. See [Event System](/react/docs/events.html) for more details.
|
||||
* The `onChange` event behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time. See [Forms](/react/docs/forms.html) for more details.
|
||||
* Form input attributes such as `value` and `checked`, as well as `textarea`. [More here](/react/docs/forms.html).
|
||||
* All event objects conform to the W3C spec, and all events (including submit) bubble correctly per the W3C spec. See [Event System](events.html) for more details.
|
||||
* The `onChange` event behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time. See [Forms](forms.html) for more details.
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
---
|
||||
id: special-non-dom-attributes
|
||||
title: Special Non-DOM Attributes
|
||||
layout: docs
|
||||
permalink: special-non-dom-attributes.html
|
||||
prev: dom-differences.html
|
||||
next: reconciliation.html
|
||||
---
|
||||
|
||||
Beside [DOM differences](/react/docs/dom-differences.html), React offers some attributes that simply don't exist in DOM.
|
||||
|
||||
- `key`: an optional, unique identifier. When your component shuffles around during `render` passes, it might be destroyed and recreated due to the diff algorithm. Assigning it a key that persists makes sure the component stays. See more [here](/react/docs/multiple-components.html#dynamic-children).
|
||||
- `ref`: see [here](/react/docs/more-about-refs.html).
|
||||
- `dangerouslySetInnerHTML`: takes an object with the key `__html` and a DOM string as value. This is mainly for cooperating with DOM string manipulation libraries. Refer to the last example on the front page.
|
||||
@@ -1,133 +0,0 @@
|
||||
---
|
||||
id: reconciliation
|
||||
title: Reconciliation
|
||||
layout: docs
|
||||
permalink: reconciliation.html
|
||||
prev: special-non-dom-attributes.html
|
||||
---
|
||||
|
||||
React key design decision is to make the API seem like it re-renders the whole app on every update. This makes writing applications a lot easier but is also an incredible challenge to make it tractable. This article explains how with powerful heuristics we managed to turn a O(n<sup>3</sup>) problem into a O(n) one.
|
||||
|
||||
|
||||
## Motivation
|
||||
|
||||
Generating the minimum number of operations to transform one tree into another is a complex and well-studied problem. The [state of the art algorithms](http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) have a complexity in the order of O(n<sup>3</sup>) where n is the number of nodes in the tree.
|
||||
|
||||
This means that displaying 1000 nodes would require in the order of one billion comparisons. This is far too expensive for our use case. To put this number in perspective, CPUs nowadays execute roughly 3 billion instruction per second. So even with the most performant implementation, we wouldn't be able to compute that diff in less than a second.
|
||||
|
||||
Since an optimal algorithm is not tractable, we implement a non-optimal O(n) algorithm using heuristics based on two assumptions:
|
||||
|
||||
1. Two components of the same class will generate similar trees and two components of different classes will generate different trees.
|
||||
2. It is possible to provide a unique key for elements that is stable across different renders.
|
||||
|
||||
In practice, these assumptions are ridiculously fast for almost all practical use cases.
|
||||
|
||||
|
||||
## Pair-wise diff
|
||||
|
||||
In order to do a tree diff, we first need to be able to diff two nodes. There are three different cases being handled.
|
||||
|
||||
|
||||
### Different Node Types
|
||||
|
||||
If the node type is different, React is going to treat them as two different sub-trees, throw away the first one and build/insert the second one.
|
||||
|
||||
```xml
|
||||
renderA: <div />
|
||||
renderB: <span />
|
||||
=> [removeNode <div />], [insertNode <span />]
|
||||
```
|
||||
|
||||
The same logic is used for custom components. If they are not of the same type, React is not going to even try at matching what they render. It is just going to remove the first one from the DOM and insert the second one.
|
||||
|
||||
```xml
|
||||
renderA: <Header />
|
||||
renderB: <Content />
|
||||
=> [removeNode <Header />], [insertNode <Content />]
|
||||
```
|
||||
|
||||
Having this high level knowledge is a very important aspect of why React diff algorithm is both fast and precise. It provides a good heuristic to quickly prune big parts of the tree and focus on parts likely to be similar.
|
||||
|
||||
It is very unlikely that a `<Header>` element is going generate a DOM that is going to look like what a `<Content>` would generate. Instead of spending time trying to match those two structures, React just re-builds the tree from scratch.
|
||||
|
||||
As a corollary, if there is a `<Header>` element at the same position in two consecutive renders, you would expect to see a very similar structure and it is worth exploring it.
|
||||
|
||||
|
||||
### DOM Nodes
|
||||
|
||||
When comparing two DOM nodes, we look at the attributes of both and can decide which of them changed in linear time.
|
||||
|
||||
```xml
|
||||
renderA: <div id="before" />
|
||||
renderB: <div id="after" />
|
||||
=> [replaceAttribute id "after"]
|
||||
```
|
||||
|
||||
Instead of treating style as an opaque string, a key-value object is used instead. This lets us update only the properties that changed.
|
||||
|
||||
```xml
|
||||
renderA: <div style={{'{{'}}color: 'red'}} />
|
||||
renderB: <div style={{'{{'}}fontWeight: 'bold'}} />
|
||||
=> [removeStyle color], [addStyle font-weight 'bold']
|
||||
```
|
||||
|
||||
After the attributes have been updated, we recurse on all the children.
|
||||
|
||||
|
||||
### Custom Components
|
||||
|
||||
We decided that the two custom components are the same. Since components are stateful, we cannot just use the new component and call it a day. React takes all the attributes from the new component and call `component[Will/Did]ReceiveProps()` on the previous one.
|
||||
|
||||
The previous component is now operational. Its `render()` method is called and the diff algorithm restarts with the new result and the previous result.
|
||||
|
||||
|
||||
## List-wise diff
|
||||
|
||||
### Problematic Case
|
||||
|
||||
In order to do children reconciliation, React adopts a very naive approach. It goes over the list of children both at the same time and whenever there's a difference generates a mutation.
|
||||
|
||||
For example if you add an element at the end:
|
||||
|
||||
```xml
|
||||
renderA: <div><span>first</span></div>
|
||||
renderB: <div><span>first</span><span>second</span></div>
|
||||
=> [insertNode <span>second</span>]
|
||||
```
|
||||
|
||||
Inserting an element at the beginning is problematic. React is going to see that both nodes are spans and therefore run into a mutation mode.
|
||||
|
||||
```xml
|
||||
renderA: <div><span>first</span></div>
|
||||
renderB: <div><span>second</span><span>first</span></div>
|
||||
=> [replaceAttribute textContent 'second'], [insertNode <span>first</span>]
|
||||
```
|
||||
|
||||
There are many algorithms that attempt to find the minimum sets of operations to transform a list of elements. [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) can find the minimum using single element insertion, deletion and substitution in O(n<sup>2</sup>). Even if we were to use Levenshtein, this doesn't find when a node has moved into another position and algorithms to do that have much worse complexity.
|
||||
|
||||
### Keys
|
||||
|
||||
In order to solve this seemingly intractable issue, an optional attribute has been introduced. You can provide for each child a key that is going to be used to do the matching. If you specify a key, React is now able to find insertion, deletion, substitution and moves in O(n) using a hash table.
|
||||
|
||||
|
||||
```xml
|
||||
renderA: <div><span key="first">first</span></div>
|
||||
renderB: <div><span key="second">second</span><span key="first">first</span></div>
|
||||
=> [insertNode <span>second</span>]
|
||||
```
|
||||
|
||||
In practice, finding a key is not really hard. Most of the time, the element you are going to display already have a unique id. When it is not the case, you can hash some parts of the content to generate an id. Remember that the id only has to be unique among its sibling, not globally unique.
|
||||
|
||||
|
||||
## Trade-offs
|
||||
|
||||
It is important to remember that the reconciliation algorithm is an implementation detail. React could re-render the whole app on every action, the end-result would be the same. We are regularly refining the heuristics in order to make common use cases faster.
|
||||
|
||||
In the current implementation, you can express the fact that a sub-tree has been moved between siblings, but you cannot tell that it has moved somewhere else. The algorithm will re-render that full sub-tree.
|
||||
|
||||
Because we rely on two heuristics, if the assumptions behind them are not met, performance will suffer.
|
||||
|
||||
1. The algorithm will not try to match sub-trees of different components classes. If you see yourself alternating between two components classes with very similar output, you may want to make it the same class. In practice, we haven't found this to be an issue.
|
||||
|
||||
2. If you don't provide stable keys (by using Math.random() for example), all the sub-trees are going to be re-rendered every single time. By giving the users the choice to chose the key, they have the ability to shoot themselves in the foot.
|
||||
|
||||
@@ -2,10 +2,7 @@
|
||||
id: tutorial
|
||||
title: Tutorial
|
||||
layout: docs
|
||||
prev: getting-started.html
|
||||
next: videos.html
|
||||
---
|
||||
|
||||
We'll be building a simple, but realistic comments box that you can drop into a blog, similar to Disqus, LiveFyre or Facebook comments.
|
||||
|
||||
We'll provide:
|
||||
@@ -35,7 +32,6 @@ For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your fav
|
||||
<title>Hello React</title>
|
||||
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
|
||||
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="content"></div>
|
||||
@@ -43,7 +39,6 @@ For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your fav
|
||||
/**
|
||||
* @jsx React.DOM
|
||||
*/
|
||||
// The above declaration must remain intact at the top of the script.
|
||||
// Your code here
|
||||
</script>
|
||||
</body>
|
||||
@@ -104,7 +99,7 @@ React.renderComponent(
|
||||
);
|
||||
```
|
||||
|
||||
Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](/react/docs/jsx-in-depth.html).
|
||||
Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](jsx-in-depth.html).
|
||||
|
||||
#### What's going on
|
||||
|
||||
@@ -210,13 +205,12 @@ Markdown is a simple way to format your text inline. For example, surrounding te
|
||||
|
||||
First, add the third-party **Showdown** library to your application. This is a JavaScript library which takes Markdown text and converts it to raw HTML. This requires a script tag in your head (which we have already included in the React playground):
|
||||
|
||||
```html{7}
|
||||
```html{6}
|
||||
<!-- template.html -->
|
||||
<head>
|
||||
<title>Hello React</title>
|
||||
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
|
||||
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
|
||||
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
|
||||
<script src="http://cdnjs.cloudflare.com/ajax/libs/showdown/0.3.1/showdown.min.js"></script>
|
||||
</head>
|
||||
```
|
||||
@@ -304,7 +298,7 @@ React.renderComponent(
|
||||
|
||||
Now that the data is available in the `CommentList`, let's render the comments dynamically:
|
||||
|
||||
```javascript{4-6,9}
|
||||
```javascript{4-6}
|
||||
// tutorial10.js
|
||||
var CommentList = React.createClass({
|
||||
render: function() {
|
||||
@@ -326,7 +320,7 @@ That's it!
|
||||
|
||||
Let's replace the hard-coded data with some dynamic data from the server. We will remove the data prop and replace it with a URL to fetch:
|
||||
|
||||
```javascript{3}
|
||||
```javascript{2}
|
||||
// tutorial11.js
|
||||
React.renderComponent(
|
||||
<CommentBox url="comments.json" />,
|
||||
@@ -375,27 +369,21 @@ When the component is first created, we want to GET some JSON from the server an
|
||||
]
|
||||
```
|
||||
|
||||
We'll use jQuery 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.
|
||||
|
||||
```javascript{6-17}
|
||||
```javascript{4-11}
|
||||
// tutorial13.js
|
||||
var CommentBox = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {data: []};
|
||||
},
|
||||
componentWillMount: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
url: 'comments.json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this),
|
||||
error: function(xhr, status, err) {
|
||||
console.error(this.props.url, status, err.toString());
|
||||
}.bind(this)
|
||||
});
|
||||
return {data: []};
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
@@ -409,15 +397,14 @@ var CommentBox = React.createClass({
|
||||
});
|
||||
```
|
||||
|
||||
Here, `componentWillMount` is a method called automatically by React before a component is rendered. The key to dynamic updates is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is trivial to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
|
||||
The key is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is trivial to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
|
||||
|
||||
```javascript{3,16-17,31}
|
||||
```javascript{3,17-21,35}
|
||||
// tutorial14.js
|
||||
var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -471,7 +458,7 @@ var CommentForm = React.createClass({
|
||||
|
||||
Let's make the form interactive. When the user submits the form, we should clear it, submit a request to the server, and refresh the list of comments. To start, let's listen for the form's submit event and clear it.
|
||||
|
||||
```javascript{3-13,16-17,21}
|
||||
```javascript{3-13,16,21}
|
||||
// tutorial16.js
|
||||
var CommentForm = React.createClass({
|
||||
handleSubmit: function() {
|
||||
@@ -517,13 +504,12 @@ When a user submits a comment, we will need to refresh the list of comments to i
|
||||
|
||||
We need to pass data from the child component to its parent. We do this by passing a `callback` in props from parent to child:
|
||||
|
||||
```javascript{12-14,28}
|
||||
```javascript{13-15,32}
|
||||
// tutorial17.js
|
||||
var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -584,13 +570,12 @@ var CommentForm = React.createClass({
|
||||
|
||||
Now that the callbacks are in place, all we have to do is submit to the server and refresh the list:
|
||||
|
||||
```javascript{13-21}
|
||||
```javascript{14-22}
|
||||
// tutorial19.js
|
||||
var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -599,7 +584,6 @@ var CommentBox = React.createClass({
|
||||
handleCommentSubmit: function(comment) {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
type: 'POST',
|
||||
data: comment,
|
||||
success: function(data) {
|
||||
@@ -632,13 +616,12 @@ var CommentBox = React.createClass({
|
||||
|
||||
Our application is now feature complete but it feels slow to have to wait for the request to complete before your comment appears in the list. We can optimistically add this comment to the list to make the app feel faster.
|
||||
|
||||
```javascript{13-15}
|
||||
```javascript{14-16}
|
||||
// tutorial20.js
|
||||
var CommentBox = React.createClass({
|
||||
loadCommentsFromServer: function() {
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
success: function(data) {
|
||||
this.setState({data: data});
|
||||
}.bind(this)
|
||||
@@ -650,7 +633,6 @@ var CommentBox = React.createClass({
|
||||
this.setState({data: newComments});
|
||||
$.ajax({
|
||||
url: this.props.url,
|
||||
dataType: 'json',
|
||||
type: 'POST',
|
||||
data: comment,
|
||||
success: function(data) {
|
||||
@@ -681,4 +663,4 @@ var CommentBox = React.createClass({
|
||||
|
||||
### Congrats!
|
||||
|
||||
You have just built a comment box in a few simple steps. Learn more about [why to use React](/react/docs/why-react.html), or dive into the [API reference](/react/docs/top-level-api.html) and start hacking! Good luck!
|
||||
You have just built a comment box in a few simple steps. Learn more about [why to use React](why-react.html), or dive into the [API reference](top-level-api.html) and start hacking! Good luck!
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
---
|
||||
id: videos
|
||||
title: Videos
|
||||
layout: docs
|
||||
permalink: videos.html
|
||||
prev: tutorial.html
|
||||
next: complementary-tools.html
|
||||
---
|
||||
|
||||
### Rethinking best practices - JSConf.eu
|
||||
|
||||
<iframe width="650" height="315" src="//www.youtube.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
"At Facebook and Instagram, we’re trying to push the limits of what’s possible on the web with React. My talk will start with a brief introduction to the framework, and then dive into three controversial topics: Throwing out the notion of templates and building views with JavaScript, “re-rendering” your entire application when your data changes, and a lightweight implementation of the DOM and events." -- [Pete Hunt](http://www.petehunt.net/)
|
||||
|
||||
### JavaScript Jabber
|
||||
|
||||
[Pete Hunt](http://www.petehunt.net/) and [Jordan Walke](https://github.com/jordwalke) talked about React in JavaScript Jabber 73.
|
||||
<figure>[](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/#content)</figure>
|
||||
|
||||
<table width="100%"><tr><td>
|
||||
01:34 – Pete Hunt Introduction<br />
|
||||
02:45 – Jordan Walke Introduction<br />
|
||||
04:15 – React<br />
|
||||
06:38 – 60 Frames Per Second<br />
|
||||
09:34 – Data Binding<br />
|
||||
12:31 – Performance<br />
|
||||
17:39 – Diffing Algorithm<br />
|
||||
19:36 – DOM Manipulation
|
||||
</td><td>
|
||||
23:06 – Supporting node.js<br />
|
||||
24:03 – rendr<br />
|
||||
26:02 – JSX<br />
|
||||
30:31 – requestAnimationFrame<br />
|
||||
34:15 – React and Applications<br />
|
||||
38:12 – React Users Khan Academy<br />
|
||||
39:53 – Making it work
|
||||
</td></tr></table>
|
||||
|
||||
[Read the full transcript](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/)
|
||||
|
||||
### Introduction to React.js - Facebook Seattle
|
||||
|
||||
<iframe width="650" height="315" src="//www.youtube.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
By [Tom Occhino](http://tomocchino.com/) and [Jordan Walke](https://github.com/jordwalke)
|
||||
|
||||
### Developing User Interfaces With React - Super VanJS
|
||||
|
||||
<iframe width="650" height="315" src="//www.youtube.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
By [Steven Luscher](https://github.com/steveluscher)
|
||||
|
||||
### Introduction to React - LAWebSpeed meetup
|
||||
|
||||
<iframe width="650" height="315" src="//www.youtube.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
by [Stoyan Stefanov](http://www.phpied.com/)
|
||||
|
||||
### "fun + React + ClojureScript" - Small Talk KyivJS Meetup
|
||||
|
||||
<iframe width="650" height="315" src="//www.youtube.com/embed/R2CGKiNnPFo" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
**In Russian** by [Alexander Solovyov](http://solovyov.net/)
|
||||
|
||||
### "Functional DOM programming" - Meteor DevShop 11
|
||||
|
||||
<iframe width="650" height="315" src="//www.youtube.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe>
|
||||
@@ -4,7 +4,7 @@ title: Downloads
|
||||
layout: single
|
||||
---
|
||||
Download the starter kit to get everything you need to
|
||||
[get started with React](/react/docs/getting-started.html). The starter kit includes React, the in-browser JSX transformer, and some simple example apps.
|
||||
[get started with React](/react/docs/getting-started.html).
|
||||
|
||||
<div class="buttons-unit downloads">
|
||||
<a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
|
||||
@@ -12,50 +12,44 @@ Download the starter kit to get everything you need to
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Development vs. Production Builds
|
||||
|
||||
We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
|
||||
|
||||
If you're just starting out, make sure to use the development version.
|
||||
|
||||
## Individual Downloads
|
||||
|
||||
#### <a href="http://fb.me/react-{{site.react_version}}.js">React {{site.react_version}} (development)</a>
|
||||
#### <a href="http://fb.me/react-{{site.react_version}}.min.js">React Core {{site.react_version}} (production)</a>
|
||||
The compressed, production version of React core
|
||||
|
||||
```html
|
||||
<script src="http://fb.me/react-{{site.react_version}}.min.js"></script>
|
||||
```
|
||||
|
||||
#### <a href="http://fb.me/react-{{site.react_version}}.js">React Core {{site.react_version}} (development)</a>
|
||||
The uncompressed, development version of React core with inline documentation.
|
||||
|
||||
```html
|
||||
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
|
||||
```
|
||||
|
||||
#### <a href="http://fb.me/react-{{site.react_version}}.min.js">React {{site.react_version}} (production)</a>
|
||||
The compressed, production version of React core.
|
||||
|
||||
```html
|
||||
<script src="http://fb.me/react-{{site.react_version}}.min.js"></script>
|
||||
```
|
||||
|
||||
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.js">React with Add-Ons {{site.react_version}} (development)</a>
|
||||
The uncompressed, development version of React with [add-ons](/react/docs/addons.html).
|
||||
|
||||
```html
|
||||
<script src="http://fb.me/react-with-addons-{{site.react_version}}.js"></script>
|
||||
```
|
||||
|
||||
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.min.js">React with Add-Ons {{site.react_version}} (production)</a>
|
||||
#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.min.js">React With Add-Ons {{site.react_version}} (production)</a>
|
||||
The compressed, production version of React with [add-ons](/react/docs/addons.html).
|
||||
|
||||
```html
|
||||
<script src="http://fb.me/react-with-addons-{{site.react_version}}.min.js"></script>
|
||||
```
|
||||
|
||||
#### <a href="http://fb.me/JSXTransformer-{{site.react_version}}.js">JSX Transformer</a>
|
||||
#### <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.
|
||||
|
||||
```html
|
||||
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
|
||||
```
|
||||
|
||||
All scripts are also available via [CDNJS](http://cdnjs.com/libraries/react/).
|
||||
All scripts are also available via [CDNJS](http://cdnjs.com/#react).
|
||||
|
||||
## Bower
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
layout: default
|
||||
title: HTML to JSX
|
||||
id: html-jsx
|
||||
---
|
||||
<div class="jsxCompiler">
|
||||
<h1>HTML to JSX Compiler</h1>
|
||||
<div id="jsxCompiler"></div>
|
||||
<script src="js/html-jsx-lib.js"></script>
|
||||
<script src="js/html-jsx.js"></script>
|
||||
</div>
|
||||
|
Before Width: | Height: | Size: 52 KiB |
|
Before Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 176 KiB |
|
Before Width: | Height: | Size: 81 KiB |
|
Before Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 9.4 KiB |
@@ -39,12 +39,8 @@ id: home
|
||||
React components implement a `render()` method that takes input data and
|
||||
returns what to display. This example uses an XML-like syntax called
|
||||
JSX. Input data that is passed into the component can be accessed by
|
||||
`render()` via `this.props`.
|
||||
</p>
|
||||
<p>
|
||||
<strong>JSX is optional and not required to use React.</strong> Try
|
||||
clicking on "Compiled JS" to see the raw JavaScript code produced by
|
||||
the JSX compiler.
|
||||
`render()` via `this.props`.<br />
|
||||
<strong>JSX is optional and not required to use React.</strong>
|
||||
</p>
|
||||
<div id="helloExample"></div>
|
||||
</div>
|
||||
@@ -54,7 +50,8 @@ id: home
|
||||
In addition to taking input data (accessed via `this.props`), a
|
||||
component can maintain internal state data (accessed via `this.state`).
|
||||
When a component's state data changes, the rendered markup will be
|
||||
updated by re-invoking `render()`.
|
||||
updated by re-invoking `render()`.<br />
|
||||
<strong>This example demonstrates use of React without JSX.</strong>
|
||||
</p>
|
||||
<div id="timerExample"></div>
|
||||
</div>
|
||||
|
||||
2602
docs/js/showdown.js
@@ -7,7 +7,7 @@ id: jsx-compiler
|
||||
<h1>JSX Compiler</h1>
|
||||
<p>
|
||||
This tool demonstrates how <a href="/react/docs/jsx-in-depth.html">JSX syntax</a>
|
||||
is desugared into native JavaScript.
|
||||
is desguared into native JavaScript.
|
||||
</p>
|
||||
<div id="jsxCompiler"></div>
|
||||
<script type="text/javascript" src="js/jsx-compiler.js"></script>
|
||||
|
||||
@@ -22,4 +22,4 @@ Many developers and users idle on Freenode.net's IRC network in **[#reactjs on f
|
||||
|
||||
[**#reactjs** hash tag on Twitter](https://twitter.com/search?q=%23reactjs) is used to keep up with the latest React news.
|
||||
|
||||
<div><a class="twitter-timeline" data-dnt="true" data-chrome="nofooter noheader transparent" href="https://twitter.com/search?q=%23reactjs" data-widget-id="342522405270470656"></a></div>
|
||||
<center><a class="twitter-timeline" data-dnt="true" data-chrome="nofooter noheader transparent" href="https://twitter.com/search?q=%23reactjs" data-widget-id="342522405270470656"></a></center>
|
||||
|
||||
@@ -10,4 +10,4 @@ The React tips section provides bite-sized information that can answer lots of q
|
||||
|
||||
## 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).
|
||||
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.
|
||||
|
||||
@@ -20,17 +20,10 @@ 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:
|
||||
|
||||
- `columnCount`
|
||||
- `fillOpacity`
|
||||
- `flex`
|
||||
- `flexGrow`
|
||||
- `flexShrink`
|
||||
- `fontWeight`
|
||||
- `lineClamp`
|
||||
- `lineHeight`
|
||||
- `opacity`
|
||||
- `order`
|
||||
- `orphans`
|
||||
- `widows`
|
||||
- `zIndex`
|
||||
- `zoom`
|
||||
|
||||
@@ -16,7 +16,6 @@ var GenericWrapper = React.createClass({
|
||||
componentDidMount: function() {
|
||||
console.log(Array.isArray(this.props.children)); // => true
|
||||
},
|
||||
|
||||
render: function() {
|
||||
return <div />;
|
||||
}
|
||||
@@ -41,7 +40,6 @@ var GenericWrapper = React.createClass({
|
||||
// length of the non-existant array wrapper!
|
||||
console.log(this.props.children.length);
|
||||
},
|
||||
|
||||
render: function() {
|
||||
return <div />;
|
||||
}
|
||||
@@ -49,5 +47,3 @@ var GenericWrapper = React.createClass({
|
||||
|
||||
React.renderComponent(<GenericWrapper>hello</GenericWrapper>, mountNode);
|
||||
```
|
||||
|
||||
To make `this.props.children` easy to deal with, we've provided the [React.Children utilities](/react/docs/top-level-api.html#react.children).
|
||||
|
||||
@@ -13,16 +13,15 @@ next: dom-event-listeners.html
|
||||
|
||||
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:**
|
||||
Bad example:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var MessageBox = React.createClass({
|
||||
getInitialState: function() {
|
||||
return {nameWithQualifier: 'Mr. ' + this.props.name};
|
||||
return {nameWithQualifier: "Mr. " + this.props.name};
|
||||
},
|
||||
|
||||
render: function() {
|
||||
return <div>{this.state.nameWithQualifier}</div>;
|
||||
}
|
||||
@@ -38,35 +37,26 @@ Better:
|
||||
|
||||
var MessageBox = React.createClass({
|
||||
render: function() {
|
||||
return <div>{'Mr. ' + this.props.name}</div>;
|
||||
return <div>{"Mr. " + this.props.name}</div>;
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
|
||||
```
|
||||
|
||||
(For more complex logic, simply isolate the computation in a method.)
|
||||
|
||||
However, it's **not** an anti-pattern if you make it clear that synchronization's not the goal here:
|
||||
For more complex logic:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var Counter = React.createClass({
|
||||
getInitialState: function() {
|
||||
// naming it initialX clearly indicates that the only purpose
|
||||
// of the passed down prop is to initialize something internally
|
||||
return {count: this.props.initialCount};
|
||||
},
|
||||
|
||||
handleClick: function() {
|
||||
this.setState({count: this.state.count + 1});
|
||||
},
|
||||
|
||||
var MessageBox = React.createClass({
|
||||
render: function() {
|
||||
return <div onClick={this.handleClick}>{this.state.count}</div>;
|
||||
return <div>{this.getNameWithQualifier(this.props.name)}</div>;
|
||||
},
|
||||
getNameWithQualifier: function(name) {
|
||||
return 'Mr. ' + name;
|
||||
}
|
||||
});
|
||||
|
||||
React.renderComponent(<Counter initialCount={7}/>, mountNode);
|
||||
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
|
||||
```
|
||||
|
||||