These tests can still be run in the browser using `grunt test --debug`.
This is a repeat of 42f8d155f8. For posterity, we
do this because Phantom has a problem with Object.freeze and the test runner
can't do __DEV__ right (because we get rid of that in the build step).
Let's start logging objects as maps for children. We may want to deprecate this
and replace it with ImmutableMap and Map data structures instead.
This should ideally be logged in the recursive function but since that loses the
scope of where these children are passed it's easier to start tracking them
here to get an idea of how frequently and where it's used.
While looking up a detail of how `transferPropsTo()` works I noticed that we never check `TransferStrategies.hasOwnProperty(thisKey)` when merging props, just `newProps.hasOwnProperty(thisKey)` and a truthy test for `TransferStrategies[thisKey]`. This means that if our `newProps` has keys like `toString`, `valueOf`, or `constructor` etc. set, we will pull these functions off `TransferStrategies` and invoke them when merging props. In most cases this will just result in a failure to merge and some code without side effects being run but in the case of `valueOf` it will actually generate an exception.
I'm thinking that setting up `this.refs` in `mountComponent` is better than `construct`. Followed the same pattern as `ReactComponent.Mixin` and nulling out
the value in `construct` and setting it to its initial value in `mountComponent`.
This bites people all of the time. Until we have a better solution, let's just make the error message more actionable (most people don't know how the DOM
gets unexpectedly mutated).
The component that gets passed into renderComponent isn't guaranteed to be the
instance that gets mounted. We want to clone the instance.
Unit tests need to reason about the mounted instance. The first code mod changes:
ReactTestUtils.renderIntoDocument(<identifier>)
into
<identifier> = ReactTestUtils.renderIntoDocument(<identifier>)
Using this scripts:
scripts/bin/codemod -m -d ~/www --extensions js \
'^(\s*)ReactTestUtils\.renderIntoDocument\(\s*([$a-zA-Z0-9_]+)\s*\)' \
'\1\2 = ReactTestUtils.renderIntoDocument(\2)'
In the second case I do the same for React.renderComponent. However, there are
alot more unnecessary matches so I only codemod if the same identifier occurs
later in the file.
scripts/bin/codemod -m -d ~/www --extensions js \
'^(\s*)React.renderComponent\(\s*([$a-zA-Z0-9_]+)\s*?,(.*?\n?.*?\s\2\b)' \
'\1\2 = React.renderComponent(\2,\3'
And one more for ReactMount.renderComponent used by internals.
scripts/bin/codemod -m -d ~/www --extensions js \
'^(\s*)ReactMount.renderComponent\(\s*([$a-zA-Z0-9_]+)\s*?,(.*?\n?.*?\s\2\b)' \
'\1\2 = ReactMount.renderComponent(\2,\3'
This still matches many unnecessary cases where the second occurance of the
identifier is a redeclaration or comment. But this code mod doesn't hurt in
those cases.
Finally I have to do the same for:
this.<identifier> = React.renderComponent(this.<identifier>,
This is a common pattern for production code but not tests. Some of these call
sites will likely break when we move to true descriptors.
scripts/bin/codemod -m -d ~/www --extensions js \
'^(\s*)React.renderComponent\((\s*)this\.([$a-zA-Z0-9\_\.]+)\s*?,' \
'\1this.\3 = React.renderComponent(\2this.\3,'
We have unexpectedly had to shut Shirtstarter down, so it won't serve as a good React.js example any more unfortunately -- sorry for the documentation churn.
This is the first step towards descriptors. This will start cloning the
component when it's mounted instead of mounting the first instance.
This avoids an issue where a reference to the first instance can hang around
in props. Since a mounted component gets mutated, the descriptor changes.
We don't need to clone the props object itself. Mutating the shallow props
object of a child that's passed into you is already flawed. Those cases need to
use cloneWithProps. A props object is considered shallow frozen after it leaves
the render it was created in.
Optimizations and fix for JSXTransformer build.
Dropped dependency on emulation of Node.js native modules.
Added deamdify step for JSXTransformer build.
We found that the component would break if we set any statics with the
value 0. It turns out @chenglou already ran into this with
d71736b3ed but the statics code was copied
earlier, and still has this falsy check. Made the same change, updated
the unittest.
After we run `require('mock-modules').dumpCache()`, the object exported by
the `emptyObject` module will no longer be identical to previously
exported objects, so tests like `expect(component.refs).toBe(emptyObject)`
will fail.
Note that this behavior only manifests itself in tests, because of course
we do not call `dumpCache` in production code.
We could consider storing the `emptyObject` globally to thwart the effects
of `dumpCache`, but it's more idiomatic simply to re-`require` the latest
version of `emptyObject`.
If no refs are rendered, `this.refs` is undefined. This is bad since it deopts & is hard to look for. Instead we should make `this.refs` an immutable empty object.
This adds an instrumentation hook for logging so that we can monitor invalid API
usage before we're ready to issue a warning.
I took the opportunity to update some console.warns to use the warning module
instead. The remaining console.warns
will be replaced by the warning module after we've cleaned up the callsites.
When IE8 focuses a disabled item, it throws
This makes sure the we're not focusing the item during selection restoration/autofocus when the element's disabled.
There were these two lists of JSX tools at Complimentary Tools
and Tooling Integration, that were a bit out of sync with each other.
Bring them together and add a link to the former from the latter.
Dealing with immutable data is hard. This provides a simple helper (ported from the IG codebase) that makes dealing with immutable JSON data easier. Designed to be familiar for people who use MongoDB.
This is part of what Sebastian suggested. We require it into every component that explicitly needs it and inject it as a default mixin for composite components in
the browser environment. This change frees us up to inject everything in ReactComponent.
Most of the time this is what you want to do, so I've renamed what was Simulate to be SimulateNative.
Now Simulate.change does what you expect, so this fixes#517 and fixes#519.
grep -rl 'Copyright 2013 Facebook' static_upstream | xargs perl -pi -w -e s/Copyright 2013 Facebook/Copyright 2013-2014 Facebook/g;'
Not going to check in a script to do this since it will just change every year.
Closes#1006
Fixes#1124.
I didn't add `volume` because it requires more complicated logic to control properly and I didn't add `paused` because to set it we need to call play() or pause() -- perhaps a mutation method is appropriate.
Two improvements: make sure we set `done = true` when an error message is
received, so that the test output contains the error message instead of
eventually timing out and displaying nothing useful; and increase the
timeout for this particular test from 5000ms (the default) to 20000ms.
reverts 23ab30ff87 because the issue it fixed doesn't seem to be a problem
anymore. textContent should be better for more things anyway, as the
original 309a88bcf6 indicates. It should be faster because innerText
requires layout.
This also allows us to use strings with newlines in our rendered output
and have confidence that they will render the same on subsequent
re-renders. This is especially useful for es6-style backtick multi-line
strings. This will be more consistent as textContent is supported almost
everwhere so we won't have differing behavior between webkit and
firefox.
see https://github.com/facebook/react/issues/1080
ReactDefaultPerf:
* Show times as float instead of string. This means they're sortable.
* Add count columns to all types and average to exclusive time.
* Include mountComponent where updateComponent time is measured.
* Increment count on _renderValidatedComponent instead of update.
ReactDefaultPerfAnalysis:
* Return counts with all summaries.
Split the summary functions into a separate module, and add the ability to view a lot of all DOM operations. Removed DOM timing since it was incorrect. Will potentially replace with a
dropped frame counter in the future.
This logs DOM ops for a given reconcile. Based on which components rendered and which ones *actually* caused DOM updates we can find
opportunities to add shouldComponentUpdate() methods.
Inclusive time is still not that helpful w/o looking at what actually resulted in DOM ops. However, this is better than what we have today and will serve as a building block.
I blacklisted everything but composite components -- hopefully that's OK.
The key idea here is that you're always rendering `this.state.children`, not
`this.props.children`. When combined with `cloneWithProps()` this means we can
keep them in the DOM as long as we want. We add new children and reactively
update existing ones using `setState()` inside of `componentWillReceiveProps()`
so `this.state.children` always has the latest versions of components. Since we
may be keeping old components around that are no longer in
`this.props.children` we need a way to figure out where they should be inside
of the combined `this.state.children` list. `ReactTransitionChildMapping` does
this for us.
Based on that infrastructure we can build the interface we always wanted: enter
and leave lifecycle hooks.
When a component is added to the DOM, `componentWillEnter(callback)` gets
called. Call the callback when you're done animating and `componentDidEnter()`
will be called.
When a component is about to be removed from the DOM,
`componentWillLeave(callback)` gets called. Call the callback when you're done
animating and `componentDidLeave()` will be called and the component will
*actually* be removed from the DOM. It won't be removed until you call the
callback.
These also handle "concurrent" changes. If you "stack" enter/leaves of a single
component before the animation has completed, it will block out all of those
animations until the current animation completes, and then finally it will
animate 0 or 1 times to get itself into the desired current state. This is what
differentiates `componentWillEnter()` from `componentDidMount()`.
The next step would be to build `componentDidReorder()`.
I've built `ReactCSSTransitionGroup` which is identical to the old
`ReactTransitionGroup` and codemodded the callsites.
With #1021 and #1022, I believe this makes it so React never wraps user code in a try/catch. I left in the calls to ReactErrorUtils.guard because it sounds like FB code finds them useful.
This creates a membrane around the React component prototype. It warns if you
try to access properties on the component before it's unmounted. Before it's
mounted, it should be considered a descriptor and not an actual instance.
The workaround, for unknown types, is to access the constructor using
component.type which has static methods on it.
All of this is provided by the react package now, so there's no point in having
it available in multiple places. We *may* go back on that in the future for
shipping test utils, but for the time being, this is better for all.
Also added tests for PooledClass.
Noticed that some places use `ReactReconcileTransaction.release(transaction)`, when `transaction` might be of another class, say `ReactServerRenderingTransaction` (still a Github PR). This catches that.
If a transaction wrapper's closer throws (such as flushBatchedUpdates in ReactDefaultBatchingStrategy) then we still want to properly deinitialize the transaction by setting isInTransaction to false. Without this, we can't reuse the transaction object (in this case, all future batched updates would fail because nested transactions aren't allowed).
Removed uglification for separate files since it significantly slowed down build (browserify:min became 26 sec instead of 110, same for :addonsMin) while gave economy in ~70 bytes for min+gz version.
The documentation states that React.renderComponentToString
'uses a callback API to keep the API async', but the
implementation is actually synchronous. In order to maintain
this contract the callback should always be called
asynchronously or be change to a synchronous API.
As per the discussion of pull request 982, the API should
be changed to a synchronous one.
Recently learned that components passed into `React.renderComponent` may not be the ones actually mounted. Also learned that it returns the mounted component. Added some documentation describing this.
Number('.1') === 0.1, and react uses dot-prefixed keys
for children. Whoops. Nuke the non-numeric requirement, and just
check a regex. This seems performant enough in micro-benchmarks:
http://jsperf.com/numericlike
We've been able to use `querySelectorAll` in all the browsers that we
support for some time now, but we haven't been able to test code that uses
it in the older version of `jsdom` that we were using, until recently.
Besides the general goal of modernizing our code, the impetus for this
specific change is that I'm trying to support testing without having to
render nodes into an actual document. The `.getElementsByName` method is
only defined on `document` and only works if the nodes you care about are
contained by the document.
On the other hand, `querySelectorAll` works on any DOM node, and allows a
more precise selection of just the `<input type="radio">` elements that
have the appropriate name.
IE8's implementation of `querySelectorAll` supports attribute-based
selectors, which is all we need here.
Little-known fact: instead of writing copies of compiled module files to
build/modules/, the bin/jsx-internal script actually just makes hard links
to the master versions of files in the .module-cache/, so re-populating
build/modules/ is very inexpensive.
Closes#856.
Rethrowing errors makes debugging harder. This makes it so that an exception in a render method can be caught using the purple stop sign (or the blue one, of course) in Chrome.
This codemods to shim any old-style JSX whitespace so that it renders the same as before.
Basically it sticks explicit `{' '}` spaces in where spaces are no longer implicit.
`cloneWithProps` uses `ReactPropTransferer`, which ignores the `key`
prop. See https://github.com/facebook/react/pull/713
However, this is not the case with `cloneWithProps` because when someone
is cloning a component and provides a key, they mean for the clone to
take it.
We've talked about this perf optimization for a while now. This prevents us from re-reconciling components that are above the component being
reconciled in the owner hierarchy.
See [Commoner's README.md](
https://github.com/benjamn/commoner#generating-multiple-files-from-one-source-module)
for further explanation of the new functionality.
Among other potential benefits, this upgrade allows us to generate source
maps as standalone files rather than appending them inline to every
compiled module file under `build/modules/` (see #833).
When React moved to attaching top-level event listeners on-demand, not all of the dependencies for `ChangeEventPlugin` were set. This led to `onChange` events not firing under certain circumstances. For example, listening to `onChange` on a checkbox will not work because it relies on `onClick` (unless something else on the page was listening to `onClick`).
The intention of the `npm-react/**/*` rule was to copy recursively but it would have flattened any nested directory structure. I changed the `build/modules` rule to copy recursively as well, which is necessary for `ReactTestUtils` to be able to require `test/mock-modules.js` successfully. (`ReactTestUtils` isn't included in a clean `npm-react` build currently but it will be in the future.)
This also makes running ART tests more practical.
It's only used here, so let's just inline this and get rid of the additional module.
Also it will make people like this guy happy: https://github.com/facebook/react/issues/900
(of course he might be even more happy if he wasn't using MS TFS....but that's a much bigger diff, and not one I can write...)
This diff introduces PropType.shape which lets you type an object. PropType.object was already defined and since it isn't a function I couldn't really overload the meaning to also accept a type list. Instead of doing hackery, I decided to name it `shape`.
An example where this could be used is style:
```
propTypes: {
style: PropTypes.shape({
color: PropStyle.string,
fontSize: PropTypes.number
})
}
```
Fixes#208. If you attempt a state update with a bad state then the render will fail (and the DOM won't change) but if you switch back to a valid state later then it'll rerender properly.
This is an alternative, less-invasive, fix for #891.
Test Plan:
On http://jsbin.com/OqOJidIQ/2/edit, got timings like
[75, 56, 30, 36, 27, 27, 28, 32, 27, 27, 28, 31]
instead of the old
[75, 729, 46, 32, 28, 34, 26, 27, 27, 30, 26, 26].
I also added a counter to getID and saw it was called 3014 times instead of the old 636264. (3014 is the number of nodes (3000) plus 3 calls that happen for the initial render and 1 for each of the 11 renders after that.)
add the ability for React propTypes to accept an `any` type: `someProp: React.PropTypes.any`.
This is more useful when combined with `.isRequired`, to enforce that _something_ is passed:
`someProp: React.PropTypes.any.isRequired`
Input elements of type `checkbox`, `hidden`, or `radio` can have a `value` without `onChange`. Also, if the input is `disabled`, who cares that it doesn't have an `onChange`?
This is a follow-up to #803.
In jsdom (used for internal testing), `<iframe>` does not properly create a default document. This makes the `EnterLeaveEventPlugin` tests work for jsdom, too.
Open source does not need this because it uses PhantomJS.
In b0431a5 I added the check in the wrong place which could cause the warning to be shown because of key changes rather than owner changes like the warning suggests.
This test is expected to throw but because of ReactErrorUtils.guard
which uses console.error in __DEV__ it also logged the invariant error
to the console. This change fixes it by temporarily stubbing out
console.error.
Fixes#531
Final part of server rendering cleanup. We should only support full-page rendering when server rendering is involved since
otherwise it's slow and can crash browsers when you start adding and removing document roots. This diff removes the magic
innerHTML code (since that will be handled by the server rendering piece) and adds the right assertions and errors.
Because there's no longer a dangerous of accidentally nuking the whole page, I removed allowFullPageRender which is yet another
internal we no longer need to expose.
These are dangerous from a cross-browser perspective. I think supporting efficient reactive updates will be prohibitively
expensive and we'll never prioritize it. Instead of killing this capability entirely, let's just throw on the dangerous cases.
There will be a few follow-up diffs
This ensures we don't add displayName in the transform if it's already been
defined. This is especially important when in strict mode, where duplicate
properties in an object is an exception.
Use the `clipboardData` object available on `window`, if it's not available on the event object. This allows us to support including the `clipboardData` in cut/copy/paste events in IE.
If you're writing a test that involves a mocked component that normally
returns a `<li>` tag from its `render` method as the root element, mocking
it with a dummy `<div>` probably won't work, so you'll want to set
MyListItemComponent.mockTagName = 'li';
The change to the `.mockImplementation` line makes sense because
`ConvenienceConstructor` is more or less synonymous (for these purposes)
with the wrapper that was previously used:
function() {
// This `this` used to be `null`, technically, but
// ConvenienceConstructor doesn't pay attention to `this` anyway.
return ConvenienceConstructor.apply(this, arguments);
}
This had a higher probability of collision than originally thought (bad math). This makes the strategy injectable and provies a
no-collision version on the client and an unlikely-to-collide version on the server.
what if you want to change the props of a child? This is my first attempt which lets you clone a child and transfer some custom props to it.
There is a fundamental issue with refs here. Since the component is cloned the ref will be broken. And since we can clone multiple times, it might not make sense to support repairing refs.
Fixes#767. This essentially reverts 738de8c.
We could store some sort of flag to silence the console error here but since we've made significant improvements in markup wrapping, this error is fairly rare now. We'll also have validation of node structure soon in #735.
- Add html5shiv so that HTML5 elements like header, footer, etc can be styled
- Remove a couple uses of :first-child/:last-child which IE8 doesn't support
Fixes#708.
Test Plan:
In IE9, tested a controlled text input with the event handler on a containing element, as in the fiddle linked in the original issue. Also tested a controlled radio button as the logic there differs within ReactDOMInput. In both cases, I was able to interact with the controls.
Now when a `key` prop appears, its value is always honored. This means that in the root component or as an only child, changing key will cause remounting; in a `children` object, the `key` prop will be joined with the object key to form a two-part key.
Fixes#590.
It changed React Playground to add a required props but unfortunately didn't update the call sites of the front-page. I don't think it should be required so I'm just making it optional and providing the correct default value.
Test Plan:
- Open the front page and make sure examples are working
- Open /react/jsx-compiler.html and make sure it is working
- Open /react/html-jsx.html and make sure it is working
Since we can use props to pass React Components, we should have a better way of validating these props than just `object`. Having a prop type `component` will allow us to safely assume that the passed prop IS a component.
This is a follow-up the to previous commit and does two things:
- Moves `ReactMount.ATTR_NAME` to `DOMProperty.ID_ATTRIBUTE_NAME`.
- Adds `DOMPropertyOperations.createMarkupForID` and uses it.
We have this really nice method for safely creating markup for an HTML
attribute, `DOMPropertyOperations.createMarkupForProperty(...)`. Let's
use it to create the ID attribute markup, too.
These should be included so that anybody can build and update the docs
with as little confusion as possible.
I've left the directory in .gitignore so additions need to be
intentional as part of a release.
This reduces the time taken by `grunt populist:test` from 7s to 550ms,
which should make @spicyj especially happy.
Relevant commits from the `populist` and `ast-types` repositories:
9863ad16c0dabef2a4ac
This fixes merging of `propTypes`, `contextTypes`, and `childContextTypes` so that we actually merge (instead of only taking the component or last mixin).
Using props to initialize state is completely fine; the issue is using state as a "cache" for values calculated based off of props. This title makes it more clear.
Chrome gives the warnings
```
body.scrollLeft is deprecated in strict mode. Please use 'documentElement.scrollLeft' if in strict mode and 'body.scrollLeft' only if in quirks mode.
body.scrollTop is deprecated in strict mode. Please use 'documentElement.scrollTop' if in strict mode and 'body.scrollTop' only if in quirks mode.
```
the first time getUnboundedScrollPosition is invoked. This fixes it. (All modern browsers support `pageYOffset`; IE 8 doesn't but works properly with `document.documentElement.scrollTop` except in quirks mode which React doesn't support.)
In the case of having an animated node which is, after the leave-transition has been activated, then re-added in a render call causes React to 'break'. This is especially noticeable if you spam to removal and re-addition of an item in a ReactTransitionGroup.
This fix simply stops the leave transition and restarts the enter transition.
This reverts https://github.com/facebook/react/pull/576
This approach mutates the default props for the instance on each update,
which causes incorrect behavior. discussed with @balpert. can look into
cloning but this unbreaks.
This leaves statics as a way to define static methods and properties
that will be accessible on the return value of `React.createClass`
without changing the current spec.
It is valuable to know when the number of children in a TransitionGroup is going
to increase or decrease, since we might want to apply extra animations.
For instance, when used with overflow:auto, we might want to apply different css
based on it overflowing or not - to do this we need to calculate this after new
nodes has entered and after nodes has been removed.
This moves the static properties off of the root object and into
a 'statics' property. Then they are made available on the constructor so
they can be used directly and in mixins.
Pull request #526 updated the behavior of vendor/constants.js without
changing any source files or the bin/jsx-internal script, so files that
should have been rebuilt (like utils/__tests__/ImmutableObject-test.js)
were not automatically rebuilt (unless you knew to do `grunt clean` or
`rm -rf .module-cache` manually).
This commit allows us to bump a version number when we know the transform
toolchain has been altered in a way that will not be visible to
commoner/jsx.
With this convention, if we reset to an older revision (e.g. during a git
bisect) and the appropriate cached module files are still in the
.module-cache/, they can be used without rebuilding. That's why I prefer
this approach to just deleting the .module-cache/.
Closes#104.
Closes#496.
Closes#530.
Summary:
e.g.
propTypes: {
foo: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]);
}
to do this, I exposed a `.weak` chainable validator that returns instead of throws, e.g.
React.PropTypes.string.isRequired.weak
React.PropTypes.string.weak
which returns true or false. Technically, `React.PropTypes.string.weak.isRequired` also exists, but `oneOfType` will never call it. Might be useful to people creating custom validators though.
Since we use keyMirror() and invariant() messages are only shown in __DEV__, we don't have to do manual constant->string translation. Also fixes a few
undefined keys that just happened to work before.
It doesn’t make much sense to generate a random key for each todo render, because it will re-draw all todo’s DOM nodes on each model change. I changed it to the unique identifier ``todo.cid`` already supplied by the backbone model.
benjamn/commoner#44 fixed commoner to work on Windows when module path relativization isn't used; with this, the `jsx` binary should work properly on Windows (though `jsx-internal` still won't).
Fixes#316, fixes#391, fixes#567.
As an added bonus, the jasmine web interface now groups tests by file.
Test Plan:
grunt test passes on b2507066, the parent of 566f8b2e (which committed a workaround for buggy module mocking).
We can already access the DOM node using `this.getDOMNode()`. Passing it as an argument was a bad decision.
Previous API:
```
componentDidMount(DOMElement rootNode)
componentDidUpdate(object prevProps, object prevState, object prevContext, DOMElement rootNode)
```
Next API:
```
componentDidMount()
componentDidUpdate(object prevProps, object prevState, object prevContext)
```
callbacks like shouldComponentUpdate, componentDidUpdate, etc. were getting the full, unsanitized context, instead of the one that's been filtered down to only the fields allowed to be visible by contextTypes.
Context is adding another argument that shifts all of them by one. Since we can already use this.getDOMNode(), it doesn't really make sense to pass it as an argument to that function.
Depends on #575; fixes#570. Now we'll be in trouble if someone tries to share objects between calls to getDefaultProps but that was already true of getInitialState and I haven't heard any complaints there.
This is the same number of allocations as before; we're just copying props in the other direction. (In any case, the copy happens only on mount and there are a couple dozen costlier things we're doing already at that time.)
This module-level mock() seems to have been interfering with other tests (26 specs failing). We don't have any other tests that do a module-level mock() so I'm going to assume it isn't supported in the open-source test runner right now. I changed it so only ReactEventEmitter.handleTopLevel is mocked; doing so made ReactEventEmitter complain that TopLevelCallbackCreator wasn't defined so I switched the ReactMount references to use React directly so that ReactDefaultInjection would kick in properly.
With this, all the tests pass.
...without preventing clicks on other things.
Just use an `<a name="...">` tag that doesn't take up any space to make sure that we're not covering up something else.
For whatever reason, doing `position: relative; top: -$navHeight;` doesn't work and causes the anchor target not to be moved up. This solution works in both Chrome and Firefox.
When events are captured, the nearest React-rendered ancestor is found and events are propagated to its tree. This causes issues when components are nested as only the innermost component receives the events.
This change modifies this behaviour so events propagate all the way up the DOM hierarchy. To reduce the performance cost, this DOM traversal is only done if the component is actually nested (determined by the `containerIsNested` map which is lazily initialised).
Summary:
adds `this.context` which you can think of as implicit props, which are passed automatically down the //ownership// hierarchy.
Contexts should be used sparingly, since they essentially allow components to communicate with descendants (in the ownership sense, not parenthood sense), which is not usually a good idea. You probably would only use contexts in places where you'd normally use a global, but contexts allow you to override them for certain view subtrees which you can't do with globals.
The context starts out `null`:
var RootComponent = React.createClass({
render: function() {
// this.context === null
}
});
You should **never** mutate the context directly, just like props and state.
You can change the context of your children (the ones you own, not `this.props.children` or via other props) using the new `withContext` method on `React`:
var RootComponent = React.createClass({
render: function() {
// this.context === null
var children = React.withContext({foo: 'a', bar: 'b'}, () => (
// In ChildComponent#render, this.context === {foo: 'a', bar: 'b'}
<ChildComponent />
));
// this.context === null
}
});
Contexts are merged, so a component can override its owner's context **for its children**:
var ChildComponent = React.createClass({
render: function() {
// this.context === {foo: 'a', bar: 'b'} (for the caller above)
var children = React.withContext({foo: 'c'},() => (
// In GrandchildComponent#render,
// this.context === {foo: 'c', bar: 'b'}
<GrandchildComponent />
));
// this.context === {foo: 'a', bar: 'b'}
}
});
Reported on Twitter by AirBnb (who are integrating React into their open-source JS framework). They made a mistake and passed a string in as the
component. We should have a better error message for that.
This renames receiveProps and changes it to take the next component to copy props from instead of just the props. That is,
component.receiveComponent(nextComponent, transaction)
instead of
component.receiveProps(nextComponent.props, transaction)
This is a precursor to adding contexts, which will also need to get propagated just like props. This change allows ReactCompositeComponent to override `receiveProps` and do something like
this._pendingContext = nextComponent.context;
Most notably, this new style of transformation gives us access to
this.parent.node, which allows us to avoid replacing identifiers that are
not actually free variables, such as member expression properties.
Closes#496.
Two of your tests were failing because of commit
1e71df5399
I fixed them by:
1) Using jasmine's spyOn in ReactCompositeComponentError-test.js
2) Inverting the function wrapping in the above commit.
Godspeed.
- Overview of add-ons for the add-ons page.
- Better title for `ReactLink`.
- Nicer code format for classSet example.
- Better explanation for `classSet`.
When we determine whether a React component should be updated (as opposed to destroyed or replaced), we currently only look at whether they share the same constructor. This adds a check for whether they share the same owner component.
I've also consolidated this logic (I cannot believe this was not already done).
dataType was unnecessary; mimeType was both unnecessary and wrong in this case. Also removed an unnecessary bind and changed pollInterval to 2000 ms for consistency with https://github.com/petehunt/react-tutorial (faster is nicer if you actually try it out!).
IE 11 no longer supports the legacy document.selection API.
Their implementation of window.getSelection() doesn't support
the extend() method, which we were relying on.
If the selection is RTL and selection extend is missing, then just
flip the selection.
The initial thought was that an opacity animation from 0.01 to 1 causes trouble on some browser. But after testing on opera 12.15, ff 23, ie 10, chrome 30, desktop/mobile safari 7 and chrome android I confirm this works.
Newer versions of WebKit and Blink will support both `document.body.scrollTop` and `document.documentElement.scrollTop`. Therefore, implementing cross-browser compatibility by summing the two will no longer work.
This changes React to use `getUnboundedScrollPosition` so we get the fix and consistency in one change!
See: https://rniwa.com/2013-10-29/web-compatibility-story-of-scrolltop-and-scrollleft/
- No need to mention React, you know you're working with it =).
- Wrap code elements in back ticks, so that they get the "box" styling for md.
- You'd want the snippet to work inside the live editor, so you need to `renderComponent`. As per wiki specification, the DOM element on which to mount is `mountNode`, just like on the front page.
- Don't forget the JSX pragma, or else your `render` fails.
- Nitpick: empty line after the end of md.
- No need for jQuery reference since
1. The general mood around React is that you don't need jQuery.
2. The syntax' still clear without jQuery.
3. We're doing a jQuery integration entry =).
- `getInitialState` was absent.
- You don't need `componentWillMount` here. fetch them in `getInitialState`.
- The non-spoken convention seems to call the event handler `"handle" + eventName`. So `handleResize` clearly indicates it's a `resize` handler while `updateDimensions` might do something else. This latter name might actually be better under circumstances where you use call the method directly somewhere, but since we removed the only direct usage in `componentWillMount` this is fine.
- Went OCD again and tried to keep the code short. `width` is enough of a demo. Removed `height`.
- Distinguish between DOM events and React events. Wish we go full React events in a near future.
When a ReactDOMComponent is created with the property `disabled: true` subsequently setting the property to `disabled: false` the HTML attribute `disabled="true"` was being left in the DOM.
If we are to unmount a component mounted into a document element we should
unmount it from document.documentElement and not from document.firstChild which
is a doctype element in this specific case.
Fixes#447.
We do this by moving the actual anchored element up in the page without moving the actual text. (Apple uses a similar trick in their framed docs.) Now this looks a bit sillier on smaller screens but it's better overall.
Currently, default props as defined by `getDefaultProps` are only used if a prop is not specified (using `X in Y` check).
However, this makes it difficult for composing components to pass along the state of not being defined, for example:
render: function() {
// If `this.props.someProp` is not set, `InnerThing` should use the default value.
return <InnerThing someProp={this.props.someProp} />;
}
This changes the requirement for falling back to the default value to an undefined check (using `typeof X === 'undefined'`).
Remember that one time I wrote release notes and said:
> This is a breaking change - if you were using class, you must change
> this to className or your components will be visually broken.
Good thing I didn't listen to myself!
We had something that did the same sort of protection. The module
differs slightly (returns document.body instead of undefined) but
looking at the callers, that should be ok.
Allow more than strings and numbers to be used as attributes for DOM
nodes. This removes the special casing for `0` and `false` that was
being used in ReactDOMInput and ReactDOMTextarea.
Now we will just `toString` any object we try to insert into a DOM.
Closes#422, #372, #302
`jsdom` behavers differently than browsers here and we should ensure
that we are consistent. Browsers should be (and are) converting to
a string first, while `jsdom` doesn't.
Forcing wrapping seems necessary here: I compared a <circle> created within a <div> with a <circle> created inside an <svg> and they appear to have exactly the same properties with the exception of .parentNode (and .parentElement), yet the former refuses to show up when appended to an <svg> element. As such, I can't find any useful way to write a unit test (testing getMarkupWrap's output doesn't seem particularly useful to me).
Fixes#311.
Test Plan:
With a component that adds a <circle> after mounting (such as http://jsfiddle.net/spicyj/hxFVe/), verify that the circle appears in both Chrome and IE9.
The injection was only evaluated when ReactCompositeComponent was first loaded.
This made it impossible to inject a custom measure and the injection pointless.
Test that React loads properly in a web worker.
Most of this code is open source-only, so I think it's safe to merge without figuring out how to translate it upstream first.
This creates a new standalone build which should have everything the
default build has, plus a little extra. This is not a sustainable long
term solution (we shouldn't make people choose like this) but it fixes
the problem we have in the short term.
This also removes the terrible react-transitions build. This is better
anway.
Fixes#369
There were 2 issues:
I was reusing event outside the original event handler (activeNativeEvent).
This is a bad idea. I've changed deferred dispatch to have an empty object
as the nativeEvent.
I didn't handle inputs without .selectionStart (e.g. file inputs). I extracted
a input type check from ChangeEventPlugin and reuse it here.
This is dangerous because it means that data is flowing into the component from two components, only one of which is the actual "owner". While we may be able to figure out how to
support this someday, let's be strict and prevent it for now.
Polyfill 'onSelect' behavior for React.
Use non-standard 'selectionchange' event rather than 'select' event.
This allows us to fire the event when user moves the cursor via arrow
keys, and not just when they select multiple chars.
Add methods to ReactDOMSelection to make getting current selection
easier, so we can do a fast check for change without having to
calculate char offsets for selection start and end.
Exposing the _renderedChildren property before all the children are fully
mounted. This allows us to debug a partially mounted tree when the debugger
has a breakpoint in the one of the mounting children.
This only has a functional difference in the case where mounting throws. This
will end up not mounting the component anyway. Any remounting shouldn't be
affected by this change.
Setting the `eventName` attribute of an element to the empty string is not
enough to cause `typeof element[eventName] === 'function'` in jsdom. The
attribute value actually has to look like a function body.
If we reconcile components higher in the hierarchy they will likely reconcile components lower in the
hierarchy. If we sort by depth then when we reach those components there will be no more pending state or
props and it will no op.
The spec for eval (http://es5.github.io/x15.1.html#x15.1.2.1) says "If Type(x) is not String, return x." and that's exactly what's happening here -- it gets {code: ...} and does nothing.
This introduces `ReactLink` which is a super lightweight way to do two-way binding for React.
If you want to use a controlled form input today, it's a lot of lines of code:
http://jsfiddle.net/T3z3v/
Look how many times `name` is repeated in there. And you have to remember to wire up event handles and pass the right state and
right event handler for *each* form field. It's really annoying.
With ReactLink, you can "link" a form value to a state field. It's just some simple sugar around the value prop/onChange
convention:
https://gist.github.com/petehunt/6689857
Ah, much nicer! And requires very little core changes or extra bytes. `ReactLink` just wraps the current value and "request
change" handler into a little object and provides some sugar to create some from composite component state.
Move compositionstart/compositionend to a new event plugin.
Add a polyfill that listens to key and mouse events and uses selection to
determine which text has changed.
Add a DOM based selection module. This can both be used on its own and
in ReactInputSelection where our current implementation is lacking.
There is still some inconsistency with how IE and modern browsers
handle block nodes. Should be OK if we are just getting and setting
and not trying to set selection based on character offsets.
This gives markdown headers an id so that we can link directly to
sections of our docs. This is better than the alternative of adding them
all ourselves.
In the IE code path the method assumed that the input.value property
was non-null. A quick fix is to use either value or innerText; which means
the same code can be shared for textarea and contentEditable components.
The code is slightly buggy because the range.parentElement() !== input check
will fail for contentEditable components when the focus within a deep DOM tree.
The selection object doesn't always have ranges. In Chrome the
selection is not updated before 'focus' event handlers are fired. See
http://jsfiddle.net/t4DYA/ for example.
The selection will have rangeCount of 0 and calling getRangeAt(0) will
throw error "Uncaught IndexSizeError: Index or size was negative, or greater
than the allowed value."
This isn't really ideal, but it makes it so that people managing to
build with @providesModule still get a consistent experience (since this
is what gets packed client-side with react-page-middleware anyway).
I am unsure how this was ever supposed to work, as testDocument is guaranteed to be undefined at that point since beforeEach doesn't run synchronously. (I don't think there's any way to have beforeEach halt the tests.)
Previously, setting textarea `value` to number 0 is treated as if `value` wasn't set at all (thus the textarea is cleared from 0 to '' upon `onChange`). `false` also renders as `"false"` instead of `""` for both `defaultValue` and `value`, on textarea _and_ input.
Created a .mailmap file with all of the associations, then used
git + perl to create the AUTHORS file. In theory these should all get
picked up by npm.
I used ABC order so it would remain unbiased and automatable. I wish we
could go back and fill out the history or at least fix the commits we
have from CommitSyncScript, but oh well.
This also includes the script I used to automate this process in the
future.
It seems like the `form="pluto"` was throwing it off and making the input live outside the form it should have been contained in, causing it to uncheck A. I added it intending to test the form attribute but ended up not needing it so removing it should be fine. (The tests were passing in phantomjs since it doesn't support the `form` attribute and simply ignored it.)
Test Plan:
grunt test; grunt test --debug
Add clipboard events to React.
For forms, these shouldn't really be necessary -- the onChange event should handle deletions and insertions. For contenteditables, however, we need to be able to access clipboard data.
getConfig needs to be a function because grunt.config.data.pkg.version isn't available at the time that grunt/config/jsx/jsx.js is required.
Test Plan:
grunt build, grunt lint, grunt test all work. After building, both react.js and react.min.js contain the version number.
Closes#271.
All three of these files are DOM-specific so it should be fine to use window. (ReactEventTopLevelCallback isn't obviously DOM-specific but it calls getEventTarget which is so I think we're fine here.)
Test Plan:
grunt test, tried events in a real browser and they seemed to work still.
Jordan warned (and StackOverflow confirmed) that IE8 doesn't respect HTML
comment nodes when setting `.innerHTML`:
http://stackoverflow.com/questions/15006001/inserting-a-comment-in-innerhtml
The virtue of the comment strategy was that the parser did all the work of
maintaining the boundaries between markup chunks, using comments as the
boundary markers. The new strategy (of tagging the first node with a
special attribute) has a similar virtue, since the parser should preserve
that attribute only for the nodes we care about, and any rendered nodes
that do not have the attribute can be ignored (and complained about by
`console.error`).
Logging every unknown property got very noisy when combined with use of `transferPropsTo`. I knew this would be a potential issue initially but decided it was worth it. Others disagreed and it's resulting in some confusion.
This changes the logging to ensure that we have a potential correction, so only DOMish properties should result in warnings.
Sencha says that separating big components into their own iframes was important for performance:
http://www.sencha.com/blog/the-making-of-fastbook-an-html5-love-story.
Today the only thing stopping us is that events don't bubble to our events system from an iframe. This diff
looks at the owning document of the container and adds top-level listeners to it. It should not change
existing behavior and should improve our support for this.
This builds `ReactTransitionGroup` with it's own copy of `React`, which
it total clownshoes. This should be technically usable, but definitely
should not be used in any production environment.
Fixed:
- New todo not submitting correctly (page refreshes. `preventDefault`
wasn't there.
- Old checked todo being removed will leave the checkmark on the next
todo replacing its position.
- Cannot change todo (`value`'s now a controlled field).
- `autofocus` (should be `autoFocus`, how ironic given the current
situation) on new todo input isn't working. Switched to manual
`focus()` in `componentDidMount` for now.
- More consistent breathing space between lines.
- Gutter at 80.
Added:
- Use todomvc-common base.css. The old one had to change ids to
classes. No longer necessary.
- Give `cx` a better name and move it in `Utils`.
- Trim input upon finishing edit.
- Remove todo if the new edited value is empty.
- Submit edited todo value on input blur.
- README to explain the existence of this example. Being able to
maintain a non-compilant version allows nice deviations from the
todomvc specs, such as animations, in the future.
We will continue using `bin/jsx-internal`, well, internally.
Note that this version no longer respects `@providesModule`, and it
doesn't do anything special with constants like `__DEV__`, so we can no
longer get to claim that `bin/jsx` can be used to build the core.
I'm happy about this, personally, because it demonstrates the flexibility
of Commoner.
This was apparently only partially supported. We had issues initially mounting if there was no HTML present and
also had issues if we had to update HTML that was already there. This diff fixes all of these cases and has
tests to prove it. NOTE: I removed a test that was actually erroneous. My bad.
HTML comment nodes are now interspersed in the original markup list so
that we can tell which chunks of markup rendered as more or less than one
node, and give a more helpful error message in that case.
Regardless of how many nodes were rendered, we only take the first one. If
zero nodes were rendered, then `resultList` will contain `null` at the
corresponding position.
If we decide to revisit the idea of using document fragments, it will be
very easy to handle the `!== 1` case by returning a document fragment.
This introduces <ReactTransitionGroup>, a component that works a lot
like Angular's ng-animate.
The problem we're currently facing is twofold:
1. We don't really have a great convention surrounding CSS transitions
in React
2. (harder) we can't animate nodes that are leaving the DOM, as their
nodes are instantly destroyed.
To solve the first issue I've adopted Angular's convention. It's
implemented in ReactTransitionableChild.
The second part is what's tricky. To do this I've implemented three modules:
- ReactTransitionableChild, which can keep its old children around if they
change to null
- ReactTransitionKeySet, which can look at a prev and next set of child
keys and merge them in a reasonable way
- ReactTransitionGroup, which combines ReactTransitionableChild and
ReactTransitionKeySet to keep nodes that are leaving the DOM in the
DOM until their animations are complete
Summary:
- Weren't pooling the Transaction in the batching strategy
- Creating a new closure for every event tick due to batchedUpdates()
- EnterLeaveEventPlugin creates a new array on each event.
I wonder if there is more optimization opportunity in accumulate(). Squinting at the fps graph this seems to be faster and waste less memory but it's hard to conclusively tell. I did verify that these were all hotspots though.
I've hit this a few times where I want to get to docs so I take whatever
my urlbar gives me and strip out the actual page so I can get to the
root, however that's a 404.
This introduces a super easy way to redirect, which could be handy in
the future as docs get rewritten.
I would much rather do this with a real htaccess file or even just
handle 404s gracefully, but that's not currently an option with GitHub
pages (since we generate our own and don't use a custom domain).
We need access to the instance cache for debugging tools. Ideally we want to
expose a more stable and supported interface but this seems like a quick win,
for now.
Sometimes you may need to detect if a value is a valid React class constructor. This enables that and prevents future consumers from getting caught in the trap of depending on an internal implementation detail we might change.
Currently this works for classes created with `React.createClass` as well as `React.DOM.*`.
This adds a `ReactDOMButton` module that shims the native `<button>` React component so it doesn't receive mouseup, mousemove, mousedown, click, or double-click events when its disabled property is truthy.
Today mixins can't easily be stateful because they can't provide getInitialState(). This allows multiple getInitialState() methods as long as they don't return objects that have conflicting keys. In that case, we throw.
`content`, `httpEquiv`, `charSet` are all needed. We're currently
working around this in `react-page`.
`content` is the risky one here since we previously supporting using
`content` to set the text content. We removed support for that in
e998041229 so the risk is minimal, there
just might be some lingering old code.
Fixes#292
Test Plan: Visit `data:text/html,<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" charset="utf-8"></head>`
```
var m = document.querySelector('meta');
m.httpEquiv; // Content-Type
m.httpEquiv = 'foo';
m.httpEquiv; // foo
m.charset; // undefined
m.charSet; // undefined
m.getAttribute('charset'); // utf-8
m.setAttribute('charset', 'bar');
m.getAttribute('charset'); // bar
m.content; // text/html; charset=utf-8
m.content = 'baz';
m.content; // baz
```
- Add pagination
- Display full content in /blog
- Truncate Recent posts
- Add permalink that lists all the blog posts
- Add spacing and bullet around recent posts to make it more readable
There are certain cases where you can end up with a collision with an implicit
key (array index) if your explicit key prop is a number. They should use
different namespaces. Therefore I wrap explicit keys in curlies and implicit
array indices in brackets.
I added a simple test case, but another case came up on the mailing list. Where
undefined entries in an array actually results in an entry and therefore an
implicit key.
Summary: Allows rendering of React into the "document" as opposed to into a
particular node. To recap some basics:
document: One level above the <html> tag - like the browser.
document.documentElement: <body>
To support full-page server side rendering, we need to be able to render
*everything* including the HTML/BODY tags. This allows that.
Closes#250.
Test Plan:
With multiple and not, verified: With defaultValue, the correct option is picked initially, user changes change the selection, and changes to defaultValue have no effect. With value, the correct option is picked initially, user changes do nothing, and changes to value change the selection.
Also ran the tests.
Many of React's util functions are non-redundant with Facebook's core
libraries, so move them out of React into a central location (out of
this repo).
These files were not getting used by any part of React core, so didn't
actually belong here anyway.
Instead of changing `traverseAllChildren`, keep that around for perf
reasons (for the hot code path `flattenChildren`)
Introduce `ReactChildren.map` and `ReactChildren.forEach`
which mirrors `Array.prototype.map` and `Array.prototype.forEach`. This
involves a rename of `mapAllChildren`
This fixes a reconciliation bug introduced by adffa9b0f4.
The new unit test case exhibits the bug. When a component that has rendered child components is updated to render inline text, we usually:
# Unmount and remove all child components.
# Set the new inline text content.
However, with batched child operations, we do not **remove all child components** until later. The current implementation will set the inline text content and blow away those nodes, causing a fatal when `ReactMultiChild` later tries to find and remove those nodes.
This fixes the bug by ensuring that text content changes are also enqueued.
The original tests were flawed because the `Danger` module exploits the fact that all React-generated markup has at least one attribute. This allows the module to extract node names from markup strings faster.
However, the tests were passing in strings of markup with no attributes.
Also, this fixes a test failure due to the test trying to set text content into a `<tr>` which is typically disallowed by browsers (and PhantomJS). This changes it to use `<td>` instead.
Not all testing environments will support setting the `innerHTML` descriptor. For example, PhantomJS initializes the `innerHTML` property as not configurable.
Setting `innerHTML` is slow: http://jsperf.com/react-child-creation/2
This reduces the number of times we set `innerHTML` by batching markup generation in a component tree.
As usual, I cleaned up the `ReactMultiChild` module significantly.
== Children Reconciliation ==
When a `ReactNativeComponent` reconciles, it compares currently rendered children, `prevChildren`, with the new children, `nextChildren`. It figures out the shortest series of updates required to render `nextChildren` where each update is one of:
- Create nodes for a new child and insert it at an index.
- Update an existing node and, if necessary, move it to an index.
- Remove an existing node.
This serializable series of updates is sent to `ReactDOMIDOperations` where the actions are actually acted on.
== Problem ==
There are two problems:
# When a `ReactNativeComponent` renders new children, it sets `innerHTML` once for each contiguous set of children.
# Each `ReactNativeComponent` renders its children in isolation, so two components that both render new children will do so separately.
For example, consider the following update:
React.renderComponent(<div><p><span /></p><p><span /></p></div>, ...);
React.renderComponent(<div><p><img /><span /><img /></p><p><img /><span /><img /></p></div>, ...);
This will trigger setting `innerHTML` four times.
== Solution ==
Instead of enqueuing the series of updates per component, this diff changes `ReactMultiChild` to enqueue updates per component tree (which works by counting recursive calls to `updateChildren`). Once all updates in the tree are accounted for, we render all markup using a single `innerHTML` set.
- 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
-`this.context` on components is now reserved for internal use by React
#### 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
* Fixed a potential XSS vulnerability when using user content as a `key`: [CVE-2013-7035](https://groups.google.com/forum/#!topic/reactjs/OIqxlB2aGfU)
## 0.5.1 (October 29, 2013)
### React
* Fixed bug with `<input type="range">` and selection events.
* Fixed bug with selection and focus.
* Made it possible to unmount components from the document root.
* Fixed bug for `disabled` attribute handling on non-`<input>` elements.
### React with Addons
* Fixed bug with transition and animation event detection.
## 0.5.0 (October 16, 2013)
### React
* Memory usage improvements - reduced allocations in core which will help with GC pauses
* Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
* Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
* Support for Selection events.
* Support for [Composition events](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
* Support for additional DOM properties (`charSet`, `content`, `form`, `httpEquiv`, `rowSpan`, `autoCapitalize`).
* Support for additional SVG properties (`rx`, `ry`).
* Support for using `getInitialState` and `getDefaultProps` in mixins.
* Support mounting into iframes.
* Bug fixes for controlled form components.
* Bug fixes for SVG element creation.
* Added `React.version`.
* Added `React.isValidClass` - Used to determine if a value is a valid component constructor.
* Removed `React.autoBind` - This was deprecated in v0.4 and now properly removed.
* Renamed `React.unmountAndReleaseReactRootNode` to `React.unmountComponentAtNode`.
* Began laying down work for refined performance analysis.
* Better support for server-side rendering - [react-page](https://github.com/facebook/react-page) has helped improve the stability for server-side rendering.
* Made it possible to use React in environments enforcing a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy). This also makes it possible to use React to build Chrome extensions.
### React with Addons (New!)
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](http://facebook.github.io/react/docs/addons.html).
### JSX
* No longer transform `class` to `className` as part of the transform! This is a breaking change - if you were using `class`, you *must* change this to `className` or your components will be visually broken.
* Added warnings to the in-browser transformer to make it clear it is not intended for production use.
* Improved compatibility for Windows
* Improved support for maintaining line numbers when transforming.
React is a JavaScript library for building user interfaces.
* **Declarative:** React uses a declarative paradigm that makes it easier to reason about your application.
* **Efficient:** React computes the minimal set of changes necessary to keep your DOM up-to-date.
* **Flexible:** React works with the libraries and frameworks that you already know.
* **Just the UI:** Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it's easy to try it out on a small feature in an existing project.
* **Virtual DOM:** React uses a *virtual DOM* diff implementation for ultra-high performance. It can also render on the server using Node.js — no heavy browser DOM required.
* **Data flow:** React implements one-way reactive data flow which reduces boilerplate and is easier to reason about than traditional data binding.
[Learn how to use React in your own project.](http://facebook.github.io/react/docs/getting-started.html)
## The `react` npm package has recently changed!
If you're looking for jeffbski's [React.js](https://github.com/jeffbski/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:
We have several examples [on the website](http://facebook.github.io/react/). Here is the first one to get you started:
```js
/** @jsx React.DOM */
varHelloMessage=React.createClass({
render:function(){
return<div>{'Hello '+this.props.name}</div>;
return<div>Hello{this.props.name}</div>;
}
});
@@ -28,7 +32,7 @@ React.renderComponent(
This example will render "Hello John" into a container on the page.
You'll notice that we used an XML-like syntax; [we call it JSX](http://facebook.github.io/react/docs/syntax.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 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.
## Installation
@@ -36,12 +40,12 @@ The fastest way to get started is to serve JavaScript from the CDN (also availab
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.4.1.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.9.0.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
If you'd like to use [bower](http://bower.io), it's as easy as:
@@ -51,7 +55,7 @@ bower install --save react
## Contribute
The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too :) Any feedback you have about using React would be greatly appreciated.
The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too. :) Any feedback you have about using React would be greatly appreciated.
### Building Your Copy of React
@@ -81,12 +85,12 @@ At this point, you should now have a `build/` directory populated with everythin
We use grunt to automate many tasks. Run `grunt -h` to see a mostly complete listing. The important ones to know:
"undefined"==typeofc.createDocumentFragment||"undefined"==typeofc.createElement}g=b}catch(d){g=j=!0}})();vare={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)returna.createDocumentFragment();
This release is the result of several months of hard work from members of the team and the community. While there are no groundbreaking changes in core, we've worked hard to improve performance and memory usage. We've also worked hard to make sure we are being consistent in our usage of DOM properties.
The biggest change you'll notice as a developer is that we no longer support `class` in JSX as a way to provide CSS classes. Since this prop was being converted to `className` at the transform step, it caused some confusion when trying to access it in composite components. As a result we decided to make our DOM properties mirror their counterparts in the JS DOM API. There are [a few exceptions](https://github.com/facebook/react/blob/master/src/dom/DefaultDOMPropertyConfig.js#L156) where we deviate slightly in an attempt to be consistent internally.
The other major change in v0.5 is that we've added an additional build - `react-with-addons` - which adds support for some extras that we've been working on including animations and two-way binding. [Read more about these addons in the docs](/react/docs/addons.html).
## Thanks to Our Community
We added *22 new people* to the list of authors since we launched React v0.4.1 nearly 3 months ago. With a total of 48 names in our `AUTHORS` file, that means we've nearly doubled the number of contributors in that time period. We've seen the number of people contributing to discussion on IRC, mailing lists, Stack Overflow, and GitHub continue rising. We've also had people tell us about talks they've given in their local community about React.
It's been awesome to see the things that people are building with React, and we can't wait to see what you come up with next!
## Changelog
### React
* Memory usage improvements - reduced allocations in core which will help with GC pauses
* Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
* Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
* Support for Selection events.
* Support for [Composition events](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
* Support for additional DOM properties (`charSet`, `content`, `form`, `httpEquiv`, `rowSpan`, `autoCapitalize`).
* Support for additional SVG properties (`rx`, `ry`).
* Support for using `getInitialState` and `getDefaultProps` in mixins.
* Support mounting into iframes.
* Bug fixes for controlled form components.
* Bug fixes for SVG element creation.
* Added `React.version`.
* Added `React.isValidClass` - Used to determine if a value is a valid component constructor.
* Removed `React.autoBind` - This was deprecated in v0.4 and now properly removed.
* Renamed `React.unmountAndReleaseReactRootNode` to `React.unmountComponentAtNode`.
* Began laying down work for refined performance analysis.
* Better support for server-side rendering - [react-page](https://github.com/facebook/react-page) has helped improve the stability for server-side rendering.
* Made it possible to use React in environments enforcing a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy). This also makes it possible to use React to build Chrome extensions.
### React with Addons (New!)
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](/react/docs/addons.html).
### JSX
* No longer transform `class` to `className` as part of the transform! This is a breaking change - if you were using `class`, you *must* change this to `className` or your components will be visually broken.
* Added warnings to the in-browser transformer to make it clear it is not intended for production use.
* Improved compatibility for Windows
* Improved support for maintaining line numbers when transforming.
This release focuses on fixing some small bugs that have been uncovered over the past two weeks. I would like to thank everybody involved, specifically members of the community who fixed half of the issues found. Thanks to [Ben Alpert][1], [Andrey Popp][2], and [Laurence Rowe][3] for their contributions!
## Changelog
### React
* Fixed bug with `<input type="range">` and selection events.
* Fixed bug with selection and focus.
* Made it possible to unmount components from the document root.
* Fixed bug for `disabled` attribute handling on non-`<input>` elements.
### React with Addons
* Fixed bug with transition and animation event detection.
React is, in my opinion, the premier way to build big, fast Web apps with JavaScript. It's scaled very well for us at Facebook and Instagram.
One of the many great parts of React is how it makes you think about apps as you build them. In this post I'll walk you through the thought process of building a searchable product data table using React.
## Start with a mock
Imagine that we already have a JSON API and a mock from our designer. Our designer apparently isn't very good because the mock looks like this:
## Step 1: break the UI into a component hierarchy
The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you're working with a designer they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!
But how do you know what should be its own component? Just use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing it should be decomposed into smaller subcomponents.
Since you're often displaying a JSON data model to a user, you'll find that if your model was built correctly your UI (and therefore your component structure) will map nicely onto it. That's because user interfaces and data models tend to adhere to the same *information architecture* which means the work of separating your UI into components is often trivial. Just break it up into components that represent exactly one piece of your data model.
You'll see here that we have five components in our simple app. I've italicized the data each component represents.
1.**`FilterableProductTable` (orange):** contains the entirety of the example
2.**`SearchBar` (blue):** receives all *user input*
3.**`ProductTable` (green):** displays and filters the *data collection* based on *user input*
4.**`ProductCategoryRow` (turquoise):** displays a heading for each *category*
5.**`ProductRow` (red):** displays a row for each *product*
If you look at `ProductTable` you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference and there's an argument to be made either way. For this example I left it as part of `ProductTable` because it is part of rendering the *data collection* which is `ProductTable`'s responsibility. However if this header grows to be complex (i.e. if we were to add affordances for sorting) it would certainly make sense to make this its own `ProductTableHeader` component.
Now that we've identified the components in our mock, let's arrange them into a hierarchy. This is easy. Components that appear within another component in the mock should appear as a child in the hierarchy:
Now that you have your component hierarchy it's time to start implementing your app. The easiest way is to build a version that takes your data model and renders the UI but has no interactivity. It's easiest to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing. We'll see why.
To build a static version of your app that renders your data model you'll want to build components that reuse other components and pass data using *props*. *props* are a way of passing data from parent to child. If you're familiar with the concept of *state*, **don't use state at all** to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app you don't need it.
You can build top-down or bottom-up. That is, you can either start with building the components higher up in the hierarchy (i.e. starting with `FilterableProductTable`) or with the ones lower in it (`ProductRow`). In simpler examples it's usually easier to go top-down and on larger projects it's easier to go bottom-up and write tests as you build.
At the end of this step you'll have a library of reusable components that render your data model. The components will only have `render()` methods since this is a static version of your app. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. If you make a change to your underlying data model and call `renderComponent()` again the UI will be updated. It's easy to see how your UI is updated and where to make changes since there's nothing complicated going on since React's **one-way data flow** (also called *one-way binding*) keeps everything modular, easy to reason about, and fast.
Simply refer to the [React docs](http://facebook.github.io/react/docs/) if you need help executing this step.
### A brief interlude: props vs state
There are two types of "model" data in React: props and state. It's important to understand the distinction between the two; skim [the official React docs](http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html) if you aren't sure what the difference is.
## Step 3: Identify the minimal (but complete) representation of UI state
To make your UI interactive you need to be able to trigger changes to your underlying data model. React makes this easy with **state**.
To build your app correctly you first need to think of the minimal set of mutable state that your app needs. The key here is DRY: *Don't Repeat Yourself*. Figure out what the absolute minimal representation of the state of your application needs to be and compute everything else you need on-demand. For example, if you're building a TODO list, just keep an array of the TODO items around; don't keep a separate state variable for the count. Instead, when you want to render the TODO count simply take the length of the TODO items array.
Think of all of the pieces of data in our example application. We have:
* The original list of products
* The search text the user has entered
* The value of the checkbox
* The filtered list of products
Let's go through each one and figure out which one is state. Simply ask three questions about each piece of data:
1. Is it passed in from a parent via props? If so, it probably isn't state.
2. Does it change over time? If not, it probably isn't state.
3. Can you compute it based on any other state or props in your component? If so, it's not state.
The original list of products is passed in as props, so that's not state. The search text and the checkbox seem to be state since they change over time and can't be computed from anything. And finally, the filtered list of products isn't state because it can be computed by combining the original list of products with the search text and value of the checkbox.
OK, so we've identified what the minimal set of app state is. Next we need to identify which component mutates, or *owns*, this state.
Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. **This is often the most challenging part for newcomers to understand,** so follow these steps to figure it out:
For each piece of state in your application:
* Identify every component that renders something based on that state.
* Find a common owner component (a single component above all the components that need the state in the hierarchy).
* Either the common owner or another component higher up in the hierarchy should own the state.
* If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.
Let's run through this strategy for our application:
*`ProductTable` needs to filter the product list based on state and `SearchBar` needs to display the search text and checked state.
* The common owner component is `FilterableProductTable`.
* It conceptually makes sense for the filter text and checked value to live in `FilterableProductTable`
Cool, so we've decided that our state lives in `FilterableProductTable`. First, add a `getInitialState()` method to `FilterableProductTable` that returns `{filterText: '', inStockOnly: false}` to reflect the initial state of your application. Then pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as a prop. Finally, use these props to filter the rows in `ProductTable` and set the values of the form fields in `SearchBar`.
You can start seeing how your application will behave: set `filterText` to `"ball"` and refresh your app. You'll see the data table is updated correctly.
So far we've built an app that renders correctly as a function of props and state flowing down the hierarchy. Now it's time to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
React makes this data flow explicit to make it easy to understand how your program works, but it does require a little more typing than traditional two-way data binding. React provides an add-on called `ReactLink` to make this pattern as convenient as two-way binding, but for the purpose of this post we'll keep everything explicit.
If you try to type or check the box in the current version of the example you'll see that React ignores your input. This is intentional, as we've set the `value` prop of the `input` to always be equal to the `state` passed in from `FilterableProductTable`.
Let's think about what we want to happen. We want to make sure that whenever the user changes the form we update the state to reflect the user input. Since components should only update their own state, `FilterableProductTable` will pass a callback to `SearchBar` that will fire whenever the state should be updated. We can use the `onChange` event on the inputs to be notified of it. And the callback passed by `FilterableProductTable` will call `setState()` and the app will be updated.
Though this sounds like a lot it's really just a few lines of code. And it's really explicit how your data is flowing throughout the app.
## And that's it
Hopefully this gives you an idea of how to think about building components and applications with React. While it may be a little more typing than you're used to, remember that code is read far more than it's written, and it's extremely easy to read this modular, explicit code. As you start to build large libraries of components you'll appreciate this explicitness and modularity, and with code reuse your lines of code will start to shrink :)
This is the 10th round-up already and React has come quite far since it was open sourced. Almost all new web projects at Khan Academy, Facebook, and Instagram are being developed using React. React has been deployed in a variety of contexts: a Chrome extension, a Windows 8 application, mobile websites, and desktop websites supporting Internet Explorer 8! Language-wise, React is not only being used within JavaScript but also CoffeeScript and ClojureScript.
The best part is that no drastic changes have been required to support all those use cases. Most of the efforts were targeted at polishing edge cases, performance improvements, and documentation.
## Khan Academy - Officially moving to React
[Joel Burget](http://joelburget.com/) announced at Hack Reactor that new front-end code at Khan Academy should be written in React!
> How did we get the rest of the team to adopt React? Using interns as an attack vector! Most full-time devs had already been working on their existing projects for a while and weren't looking to try something new at the time, but our class of summer interns was just arriving. For whatever reason, a lot of them decided to try React for their projects. Then mentors became exposed through code reviews or otherwise touching the new code. In this way React knowledge diffused to almost the whole team over the summer.
>
> Since the first React checkin on June 5, we've somehow managed to accumulate 23500 lines of jsx (React-flavored js) code. Which is terrifying in a way - that's a lot of code - but also really exciting that it was picked up so quickly.
>
> We held three meetings about how we should proceed with React. At the first two we decided to continue experimenting with React and deferred a final decision on whether to adopt it. At the third we adopted the policy that new code should be written in React.
>
> I'm excited that we were able to start nudging code quality forward. However, we still have a lot of work to do! One of the selling points of this transition is adopting a uniform frontend style. We're trying to upgrade all the code from (really old) pure jQuery and (regular old) Backbone views / Handlebars to shiny React. At the moment all we've done is introduce more fragmentation. We won't be gratuitously updating working code (if it ain't broke, don't fix it), but are seeking out parts of the codebase where we can shoot two birds with one stone by rewriting in React while fixing bugs or adding functionality.
>
> [Read the full article](http://joelburget.com/backbone-to-react/)
## React: Rethinking best practices
[Pete Hunt](http://www.petehunt.net/)'s talk at JSConf EU 2013 is now available in video.
[Stoyan Stefanov](http://www.phpied.com/)'s series of articles on React has two new entries on how to execute React on the server to generate the initial page load.
> This post is an initial hack to have React components render server-side in PHP.
>
> - Problem: Build web UIs
> - Solution: React
> - Problem: UI built in JS is anti-SEO (assuming search engines are still noscript) and bad for perceived performance (blank page till JS arrives)
> - Solution: [React page](https://github.com/facebook/react-page) to render the first view
> - Problem: Can't host node.js apps / I have tons of PHP code
> - Solution: Use PHP then!
>
> [**Read part 1 ...**](http://www.phpied.com/server-side-react-with-php/)
>
> [**Read part 2 ...**](http://www.phpied.com/server-side-react-with-php-part-2/)
Webkit has a [TodoMVC Benchmark](https://github.com/WebKit/webkit/tree/master/PerformanceTests/DoYouEvenBench) that compares different frameworks. They recently included React and here are the results (average of 10 runs in Chrome 30):
- **AngularJS:** 4043ms
- **AngularJSPerf:** 3227ms
- **BackboneJS:** 1874ms
- **EmberJS:** 6822ms
- **jQuery:** 14628ms
- **React:** 2864ms
- **VanillaJS:** 5567ms
[Try it yourself!](http://www.petehunt.net/react/tastejs/benchmark.html)
Please don't take those numbers too seriously, they only reflect one very specific use case and are testing code that wasn't written with performance in mind.
Even though React scores as one of the fastest frameworks in the benchmark, the React code is simple and idiomatic. The only performance tweak used is the following function:
```javascript
/**
* This is a completely optional performance enhancement that you can implement
* on any React component. If you were to delete this method the app would still
* work correctly (and still be very performant!), we just use it as an example
* of how little code it takes to get an order of magnitude performance improvement.
By default, React "re-renders" all the components when anything changes. This is usually fast enough that you don't need to care. However, you can provide a function that can tell whether there will be any change based on the previous and next states and props. If it is faster than re-rendering the component, then you get a performance improvement.
The fact that you can control when components are rendered is a very important characteristic of React as it gives you control over its performance. We are going to talk more about performance in the future, stay tuned.
## Guess the filter
[Connor McSheffrey](http://conr.me) implemented a small game using React. The goal is to guess which filter has been used to create the Instagram photo.
[Andrew Betts](http://trib.tv/), director of the [Financial Times Labs](http://labs.ft.com/), posted an article comparing [FruitMachine](https://github.com/ftlabs/fruitmachine) and React.
> Eerily similar, no? Maybe Facebook was inspired by Fruit Machine (after all, we got there first), but more likely, it just shows that this is a pretty decent way to solve the problem, and great minds think alike. We're graduating to a third phase in the evolution of web best practice - from intermingling of markup, style and behaviour, through a phase in which those concerns became ever more separated and encapsulated, and finally to a model where we can do that separation at a component level. Developments like Web Components show the direction the web community is moving, and frameworks like React and Fruit Machine are in fact not a lot more than polyfills for that promised behaviour to come.
>
> [Read the full article...](http://labs.ft.com/2013/10/client-side-layout-engines-react-vs-fruitmachine/)
Even though we weren't inspired by FruitMachine (React has been used in production since before FruitMachine was open sourced), it's great to see similar technologies emerging and becoming popular.
## React Brunch
[Matthew McCray](http://elucidata.net/) implemented [react-brunch](https://npmjs.org/package/react-brunch), a JSX compilation step for [Brunch](http://brunch.io/).
> Adds React support to brunch by automatically compiling `*.jsx` files.
>
> You can configure react-brunch to automatically insert a react header (`/** @jsx React.DOM */`) into all `*.jsx` files. Disabled by default.
>
> Install the plugin via npm with `npm install --save react-brunch`.
I'm going to start adding a tweet at the end of each round-up. We'll start with this one:
<blockquote class="twitter-tweet"><p>This weekend <a href="https://twitter.com/search?q=%23angular&src=hash">#angular</a> died for me. Meet new king <a href="https://twitter.com/search?q=%23reactjs&src=hash">#reactjs</a></p>— Eldar Djafarov ッ (@edjafarov) <a href="https://twitter.com/edjafarov/statuses/397033796710961152">November 3, 2013</a></blockquote>
This round-up is the proof that React has taken off from its Facebook's root: it features three in-depth presentations of React done by external people. This is awesome, keep them coming!
## Super VanJS 2013 Talk
[Steve Luscher](https://github.com/steveluscher) working at [LeanPub](https://leanpub.com/) made a 30 min talk at [Super VanJS](https://twitter.com/vanjs). He does a remarkable job at explaining why React is so fast with very exciting demos using the HTML5 Audio API.
[Connor McSheffrey](http://connormcsheffrey.com/) and [Cheng Lou](https://github.com/chenglou) added a new section to the documentation. It's a list of small tips that you will probably find useful while working on React. Since each article is very small and focused, we [encourage you to contribute](http://facebook.github.io/react/tips/introduction.html)!
- [Maximum Number of JSX Root Nodes](http://facebook.github.io/react/tips/maximum-number-of-jsx-root-nodes.html)
- [Shorthand for Specifying Pixel Values in style props](http://facebook.github.io/react/tips/style-props-value-px.html)
- [Type of the Children props](http://facebook.github.io/react/tips/children-props-type.html)
- [Value of null for Controlled Input](http://facebook.github.io/react/tips/controlled-input-null-value.html)
- [`componentWillReceiveProps` Not Triggered After Mounting](http://facebook.github.io/react/tips/componentWillReceiveProps-not-triggered-after-mounting.html)
- [Props in getInitialState Is an Anti-Pattern](http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html)
- [DOM Event Listeners in a Component](http://facebook.github.io/react/tips/dom-event-listeners.html)
- [Load Initial Data via AJAX](http://facebook.github.io/react/tips/initial-ajax.html)
- [False in JSX](http://facebook.github.io/react/tips/false-in-jsx.html)
## Intro to the React Framework
[Pavan Podila](http://blog.pixelingene.com/) wrote an in-depth introduction to React on TutsPlus. This is definitively worth reading.
> Within a component-tree, data should always flow down. A parent-component should set the props of a child-component to pass any data from the parent to the child. This is termed as the Owner-Owned pair. On the other hand user-events (mouse, keyboard, touches) will always bubble up from the child all the way to the root component, unless handled in between.
> [Read the full article ...](http://dev.tutsplus.com/tutorials/intro-to-the-react-framework--net-35660)
## 140-characters textarea
[Brian Kim](https://github.com/brainkim) wrote a small textarea component that gradually turns red as you reach the 140-characters limit. Because he only changes the background color, React is smart enough not to mess with the text selection.
<p data-height="178" data-theme-id="0" data-slug-hash="FECGb" data-user="brainkim" data-default-tab="result" class='codepen'>See the Pen <a href='http://codepen.io/brainkim/pen/FECGb'>FECGb</a> by Brian Kim (<a href='http://codepen.io/brainkim'>@brainkim</a>) on <a href='http://codepen.io'>CodePen</a></p>
[Eric Clemmons](http://ericclemmons.github.io/) is working on a "Modern, opinionated, full-stack starter kit for rapid, streamlined application development". The version 0.4.0 has just been released and has first-class support for React.
[Robert Zaremba](http://rz.scale-it.pl/) working on [AgFlow](http://www.agflow.com/) recently talked in Poland about React.
> In a nutshell, I presented why we chose React among other available options (ember.js, angular, backbone ...) in AgFlow, where I’m leading an application development.
>
> During the talk a wanted to highlight that React is not about implementing a Model, but a way to construct visible components with some state. React is simple. It is super simple, you can learn it in 1h. On the other hand what is model? Which functionality it should provide? React does one thing and does it the best (for me)!
>
> [Read the full article...](http://rz.scale-it.pl/2013/10/20/frontend_components_in_react.html)
[Todd Kennedy](http://tck.io/) working at Condé Nast wrote [JSXHint](https://github.com/CondeNast/JSXHint) and explains in a blog post his perspective on JSX.
> Lets start with the elephant in the room: JSX?
> Is this some sort of template language? Specifically no. This might have been the first big stumbling block. What looks like to be a templating language is actually an in-line DSL that gets transpiled directly into JavaScript by the JSX transpiler.
>
> Creating elements in memory is quick -- copying those elements into the DOM is where the slowness occurs. This is due to a variety of issues, most namely reflow/paint. Changing the items in the DOM causes the browser to re-paint the display, apply styles, etc. We want to keep those operations to an absolute minimum, especially if we're dealing with something that needs to update the DOM frequently.
>
> [Read the full article...](http://tck.io/posts/jsxhint_and_react.html)
## Photo Gallery
[Maykel Loomans](http://miekd.com/), designer at Instagram, wrote a gallery for photos he shot using React.
<div style="width: 320px;"><blockquote class="twitter-tweet"><p>I think this reversed gif of Steve Urkel best describes my changing emotions towards the React Lib <a href="http://t.co/JoX0XqSXX3">http://t.co/JoX0XqSXX3</a></p>— Ryan Seddon (@ryanseddon) <a href="https://twitter.com/ryanseddon/statuses/398572848802852864">November 7, 2013</a></blockquote></div>
Today we're releasing an update to address a potential XSS vulnerability that can arise when using user data as a `key`. Typically "safe" data is used for a `key`, for example, an id from your database, or a unique hash. However there are cases where it may be reasonable to use user generated content. A carefully crafted piece of content could result in arbitrary JS execution. While we make a very concerted effort to ensure all text is escaped before inserting it into the DOM, we missed one case. Immediately following the discovery of this vulnerability, we performed an audit to ensure we this was the only such vulnerability.
This only affects v0.5.x and v0.4.x. Versions in the 0.3.x family are unaffected.
Updated versions are available for immediate download via npm, bower, and on our [download page][download].
We take security very seriously at Facebook. For most of our products, users don't need to know that a security issue has been fixed. But with libraries like React, we need to make sure developers using React have access to fixes to keep their users safe.
While we've encouraged responsible disclosure as part of [Facebook's whitehat bounty program][bounty] since we launched, we don't have a good process for notifying our users. Hopefully we don't need to use it, but moving forward we'll set up a little bit more process to ensure the safety of our users. Ember.js has [an excellent policy][ember] which we may use as our model.
You can learn more about the vulnerability discussed here: [CVE-2013-7035][cve].
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)
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?
> [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
> [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.
[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.
[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.
[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.
[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>
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.
[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.
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.
[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!
[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.
[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!
> [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>
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).
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.
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).
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.
[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.
> 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.
[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.
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>
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):
[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.
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.
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>
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):
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>
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
- `this.context` on components is now reserved for internal use by React
#### 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, `.dataTransfer` 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
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
- `this.context` on components is now reserved for internal use by React
#### 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, `.dataTransfer` 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
It's exciting to see the number of real-world React applications and components skyrocket over the past months! This community round-up features a few examples of inspiring React applications and components.
## React in the Real World
### Facebook Lookback video editor
Large parts of Facebook's web frontend are already powered by React. The recently released Facebook [Lookback video and its corresponding editor](https://www.facebook.com/lookback/edit/) are great examples of a complex, real-world React app.
### Russia's largest bank is now powered by React
Sberbank, Russia's largest bank, recently switched large parts of their site to use React, as detailed in [this post by Vyacheslav Slinko](https://groups.google.com/forum/#!topic/reactjs/Kj6WATX0atg).
### Relato
[Relato](http://bripkens.github.io/relato/) by [Ben Ripkens](https://github.com/bripkens) shows Open Source Statistics based on npm data. It features a filterable and sortable table built in React. Check it out – it's super fast!
### Makona Editor
John Lynch ([@johnrlynch](https://twitter.com/johnrlynch)) created Makona, a block-style document editor for the web. Blocks of different content types comprise documents, authored using plain markup. At the switch of a toggle, block contents are then rendered on the page. While not quite a WYSIWYG editor, Makona uses plain textareas for input. This makes it compatible with a wider range of platforms than traditional rich text editors.
React is in no way limited to just web pages. Brandon Tilley ([@BinaryMuse](https://twitter.com/BinaryMuse)) just released a detailed walk-through of [how he built his Chrome extension "Fast Tab Switcher" using React](http://brandontilley.com/2014/02/24/creating-chrome-extensions-with-react.html).
### Twitter Streaming Client
Javier Aguirre ([@javaguirre](https://twitter.com/javaguirre)) put together a simple [twitter streaming client using node, socket.io and React](http://javaguirre.net/2014/02/11/twitter-streaming-api-with-node-socket-io-and-reactjs/).
### Sproutsheet
[Sproutsheet](http://sproutsheet.com/) is a gardening calendar. You can use it to track certain events that happen in the life of your plants. It's currently in beta and supports localStorage, and data/image import and export.
### Instant Domain Search
[Instant Domain Search](https://instantdomainsearch.com/) also uses React. It sure is instant!
### SVG-based graphical node editor
[NoFlo](http://noflojs.org/) and [Meemoo](http://meemoo.org/) developer [Forresto Oliphant](http://www.forresto.com/) built an awesome SVG-based [node editor](http://forresto.github.io/prototyping/react/) in React.
Rafał Cieślak ([@Ravicious](https://twitter.com/Ravicious)) wrote a [React version](http://ravicious.github.io/ultimate-ttt/) of [Ultimate Tic Tac Toe](http://mathwithbaddrawings.com/2013/06/16/ultimate-tic-tac-toe/). Find the source [here](https://github.com/ravicious/ultimate-ttt).
### ReactJS Gallery
[Emanuele Rampichini](https://github.com/lele85)'s [ReactJS Gallery](https://github.com/lele85/ReactGallery) is a cool demo app that shows fullscreen images from a folder on the server. If the folder content changes, the gallery app updates via websockets.
[Table Sorter](http://bgerm.github.io/react-table-sorter-demo/) by [bgerm](https://github.com/bgerm) [[source](https://github.com/bgerm/react-table-sorter-demo)] is another helpful React component.
### Static-search
Dmitry Chestnykh [@dchest](https://twitter.com/dchest) wrote a [static search indexer](https://github.com/dchest/static-search) in Go, along with a [React-based web front-end](http://www.codingrobots.com/search/) that consumes search result via JSON.
### Lorem Ipsum component
[Martin Andert](https://github.com/martinandert) created [react-lorem-component](https://github.com/martinandert/react-lorem-component), a simple component for all your placeholding needs.
### Input with placeholder shim
[react-input=placeholder](https://github.com/enigma-io/react-input-placeholder) by [enigma-io](https://github.com/enigma-io) is a small wrapper around React.DOM.input that shims in placeholder functionality for browsers that don't natively support it.
### diContainer
[dicontainer](https://github.com/SpektrumFM/dicontainer) provides a dependency container that lets you inject Angular-style providers and services as simple React.js Mixins.
## React server rendering
Ever wonder how to pre-render React components on the server? [react-server-example](https://github.com/mhart/react-server-example) by Michael Hart ([@hichaelmart](http://twitter.com/hichaelmart)) walks through the necessary steps.
Similarly, Alan deLevie ([@adelevie](https://twitter.com/adelevie)) created [react-client-server-starter](https://github.com/adelevie/react-client-server-starter), another detailed walk-through of how to server-render your app.
## Random Tweet
<div><blockquote class="twitter-tweet" lang="en"><p>Recent changes: web ui is being upgraded to [#reactjs](https://twitter.com/search?q=%23reactjs&src=hash), HEAD~4 at [https://camlistore.googlesource.com/camlistore/](https://camlistore.googlesource.com/camlistore/)</p>— Camlistore (@Camlistore) <a href="https://twitter.com/Camlistore/status/423925795820539904">January 16, 2014</a></blockquote></div>
In this Round-up, we are taking a few closer looks at React's interplay with different frameworks and architectures.
## "Little framework BIG splash"
Let's start with yet another refreshing introduction to React: Craig Savolainen ([@maedhr](https://twitter.com/maedhr)) walks through some first steps, demonstrating [how to build a Google Maps component](http://infinitemonkeys.influitive.com/little-framework-big-splash) using React.
[Architecting your app with react](http://lincolnloop.com/blog/architecting-your-app-react-part-1/)
We're looking forward to part 2!
> React is not a full MVC framework, and this is actually one of its strengths. Many who adopt React choose to do so alongside their favorite MVC framework, like Backbone. React has no opinions about routing or syncing data, so you can easily use your favorite tools to handle those aspects of your frontend application. You'll often see React used to manage specific parts of an application's UI and not others. React really shines, however, when you fully embrace its strategies and make it the core of your application's interface.
>
> [Read the full article...](http://lincolnloop.com/blog/architecting-your-app-react-part-1/)
## React vs. async DOM manipulation
Eliseu Monar ([@eliseumds](https://twitter.com/eliseumds))'s post "[ReactJS vs async concurrent rendering](http://eliseu.tk/post/77843550010/vitalbox-pchr-reactjs-vs-async-concurrent-rendering)" is a great example of how React quite literally renders a whole array of common web development work(arounds) obsolete.
## React, Scala and the Play Framework
[Matthias Nehlsen](http://matthiasnehlsen.com/) wrote a detailed introductory piece on [React and the Play Framework](http://matthiasnehlsen.com/blog/2014/01/05/play-framework-and-facebooks-react-library/), including a helpful architectural diagram of a typical React app.
Nehlsen's React frontend is the second implementation of his chat application's frontend, following an AngularJS version. Both implementations are functionally equivalent and offer some perspective on differences between the two frameworks.
In [another article](http://matthiasnehlsen.com/blog/2014/01/24/scala-dot-js-and-reactjs/), he walks us through the process of using React with scala.js to implement app-wide undo functionality.
Also check out his [talk](http://m.ustream.tv/recorded/42780242) at Ping Conference 2014, in which he walks through a lot of the previously content in great detail.
## React and Backbone
The folks over at [Venmo](https://venmo.com/) are using React in conjunction with Backbone.
Thomas Boyt ([@thomasaboyt](https://twitter.com/thomasaboyt)) wrote [this detailed piece](http://www.thomasboyt.com/2013/12/17/using-reactjs-as-a-backbone-view.html) about why React and Backbone are "a fantastic pairing".
## React vs. Ember
Eric Berry ([@coderberry](https://twitter.com/coderberry)) developed Ember equivalents for some of the official React examples. Read his post for a side-by-side comparison of the respective implementations: ["Facebook React vs. Ember"](http://instructure.github.io/blog/2013/12/17/facebook-react-vs-ember/).
## React and plain old HTML
Daniel Lo Nigro ([@Daniel15](https://twitter.com/Daniel15)) created [React-Magic](https://github.com/reactjs/react-magic), which leverages React to ajaxify plain old html pages and even [allows CSS transitions between pageloads](http://stuff.dan.cx/facebook/react-hacks/magic/red.php).
> React-Magic intercepts all navigation (link clicks and form posts) and loads the requested page via an AJAX request. React is then used to "diff" the old HTML with the new HTML, and only update the parts of the DOM that have been changed.
>
> [Check out the project on GitHub...](https://github.com/reactjs/react-magic)
On a related note, [Reactize](https://turbo-react.herokuapp.com/) by Ross Allen ([@ssorallen](https://twitter.com/ssorallen)) is a similarly awesome project: A wrapper for Rails' [Turbolinks](https://github.com/rails/turbolinks/), which seems to have inspired John Lynch ([@johnrlynch](https://twitter.com/johnrlynch)) to then create [a server-rendered version using the JSX transformer in Rails middleware](http://www.rigelgroupllc.com/blog/2014/01/12/react-jsx-transformer-in-rails-middleware/).
## React and Object.observe
Check out [François de Campredon](https://github.com/fdecampredon)'s implementation of [TodoMVC based on React and ES6's Object.observe](https://github.com/fdecampredon/react-observe-todomvc/).
## React and Angular
Ian Bicking ([@ianbicking](https://twitter.com/ianbicking)) of Mozilla Labs [explains why he "decided to go with React instead of Angular.js"](https://plus.google.com/+IanBicking/posts/Qj8R5SWAsfE).
### ng-React Update
[David Chang](https://github.com/davidchang) works through some performance improvements of his [ngReact](https://github.com/davidchang/ngReact) project. His post ["ng-React Update - React 0.9 and Angular Track By"](http://davidandsuzi.com/ngreact-update/) includes some helpful advice on boosting render performance for Angular components.
> Angular gives you a ton of functionality out of the box - a full MV* framework - and I am a big fan, but I'll admit that you need to know how to twist the right knobs to get performance.
>
> That said, React gives you a very strong view component out of the box with the performance baked right in. Try as I did, I couldn't actually get it any faster. So pretty impressive stuff.
>
>[Read the full post...](http://davidandsuzi.com/ngreact-update/)
React was also recently mentioned at ng-conf, where the Angular team commented on React's concept of the virtual DOM:
Jonathan Krause ([@jonykrause](https://twitter.com/jonykrause)) offers his thoughts regarding [parallels between React and Web Components](http://jonykrau.se/posts/the-value-of-react), highlighting the value of React's ability to render pages on the server practically for free.
## Immutable React
[Peter Hausel](http://pk11.kinja.com/) shows how to build a Wikipedia auto-complete demo based on immutable data structures (similar to [mori](https://npmjs.org/package/mori)), really taking advantage of the framework's one-way reactive data binding:
> Its truly reactive design makes DOM updates finally sane and when combined with persistent data structures one can experience JavaScript development like it was never done before.
> [Read the full post](http://tech.kinja.com/immutable-react-1495205675)
## D3 and React
[Ben Smith](http://10consulting.com/) built some great SVG-based charting components using a little less of D3 and a little more of React: [D3 and React - the future of charting components?](http://10consulting.com/2014/02/19/d3-plus-reactjs-for-charting/)
## Om and React
Josh Haberman ([@joshhaberman](https://twitter.com/JoshHaberman)) discusses performance differences between React, Om and traditional MVC frameworks in "[A closer look at OM vs React performance](http://blog.reverberate.org/2014/02/on-future-of-javascript-mvc-frameworks.html)".
Speaking of Om: [Omchaya](https://github.com/sgrove/omchaya) by Sean Grove ([@sgrove](https://twitter.com/sgrove)) is a neat Cljs/Om example project.
## Random Tweets
<div><blockquote class="twitter-tweet" lang="en"><p>Worked for 2 hours on a [@react_js](https://twitter.com/react_js) app sans internet. Love that I could get stuff done with it without googling every question.</p>— John Shimek (@varikin) <a href="https://twitter.com/varikin/status/436606891657949185">February 20, 2014</a></blockquote></div>
@@ -84,8 +84,8 @@ We've found that the best solution for this problem is to generate markup direct
**JSX lets you write JavaScript function calls with HTML syntax.** To generate a link in React using pure JavaScript you'd write: `React.DOM.a({href: 'http://facebook.github.io/react/'}, 'Hello React!')`. With JSX this becomes `<a href="http://facebook.github.io/react/">Hello React!</a>`. We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.**
JSX is very small; the "hello, world" example above uses every feature of JSX. To learn more about it, see [JSX in depth](./jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
JSX is very small; the "hello, world" example above uses every feature of JSX. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](./jsx-gotchas.html) for some key differences.
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
The easiest way to get started with JSX is to use the in-browser `JSXTransformer`. We strongly recommend that you don't use this in production. You can precompile your code using our command-line [react-tools](http://npmjs.org/package/react-tools) package.
JSX is a JavaScript XML syntax transform recommended for use
with React.
> Note:
>
> Don't forget the `/** @jsx React.DOM */` pragma at the beginning of your file! This tells JSX to process the file for React.
>
> If you don't include the pragma, your source will remain untouched, so it's safe to run the JSX transformer on all JS files in your codebase if you want to.
## Why JSX?
@@ -53,9 +58,11 @@ var app = Nav({color:"blue"}, Profile(null, "click"));
```
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
desugars into native JavaScript.
desugars into native JavaScript, and the
[HTML to JSX converter](/react/html-jsx.html) to convert your existing HTML to
JSX.
If you want to use JSX, the [Getting Started](getting-started.html) guide shows
If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows
how to setup compilation.
> Note:
@@ -92,7 +99,10 @@ var MyComponent = React.createClass({/*...*/});
varapp=<MyComponentsomeProperty={true}/>;
```
See [Multiple Components](multiple-components.html) to learn more about using composite components.
JSX will infer the component's name from the variable assignment and specify
the class's [displayName](/react/docs/component-specs.html#displayName) accordingly.
See [Multiple Components](/react/docs/multiple-components.html) to learn more about using composite components.
> Note:
>
@@ -157,19 +167,6 @@ It's easy to add comments within your JSX; they're just JS expressions:
varcontent=<Container>{/* this is a comment */}<Nav/></Container>;
```
## Tooling
Beyond the compilation step, JSX does not require any special tools.
* Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
* JSX syntax highlighting is available for Sublime Text and other editors
that support `*.tmLanguage` using the third-party
[`JavaScript (JSX).tmLanguage`][1].
* Linting provides accurate line numbers after compiling without sourcemaps.
* Elements use standard scoping so linters can find usage of out-of-scope
JSX looks like HTML but there are some important differences you may run into.
## 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 `{' '}`.
@@ -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.
`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.
### Child Reconciliation
@@ -124,7 +124,7 @@ The situation gets more complicated when the children are shuffled around (as in
varresults=this.props.results;
return(
<ol>
{this.results.map(function(result){
{results.map(function(result){
return<likey={result.id}>{result.text}</li>;
})}
</ol>
@@ -134,6 +134,26 @@ 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(){
varitems={};
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
@@ -144,7 +164,7 @@ In React, data flows from owner to owned component through `props` as discussed
You may be thinking that it's expensive to react to changing data if there are a large number of nodes under an owner. The good news is that JavaScript is fast and `render()` methods tend to be quite simple, so in most applications this is extremely fast. Additionally, the bottleneck is almost always the DOM mutation and not JS execution and React will optimize this for you using batching and change detection.
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](component-specs.html) for more information.
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](/react/docs/component-specs.html) for more information.
@@ -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, an error will be thrown. 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, 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:
```javascript
React.createClass({
@@ -26,22 +26,48 @@ React.createClass({
optionalObject:React.PropTypes.object,
optionalString:React.PropTypes.string,
// You can ensure that your prop is limited to specific values by treating
With `React.PropTypes.component` you can specify that only a single child can be passed to
a component as children.
```javascript
varMyComponent=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](./working-with-the-browser.html) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed.
One common use case is a component wanting to update itself on a time interval. It's easy to use `setInterval()`, but it's important to cancel your interval when you don't need it anymore to save memory. React provides [lifecycle methods](/react/docs/working-with-the-browser.html#component-lifecycle) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed.
@@ -87,7 +87,7 @@ If you want to initialize the component with a non-empty value, you can supply a
This example will function much like the **Controlled Components** example above.
Likewise, `<input>` supports `defaultChecked` and `<option>` supports `defaultSelected`.
Likewise, `<input>` supports `defaultChecked` and `<select>` supports `defaultValue`.
## Advanced Topics
@@ -130,3 +130,18 @@ For HTML, this easily allows developers to supply multiline values. However, sin
```
If you *do* decide to use children, they will behave like `defaultValue`.
### Why Select Value?
The selected `<option>` in an HTML `<select>` is normally specified through that option's `selected` attribute. In React, in order to make components easier to manipulate, the following format is adopted instead:
```javascript
<selectvalue="B">
<optionvalue="A">Apple</option>
<optionvalue="B">Banana</option>
<optionvalue="C">Cranberry</option>
</select>
```
To make an uncontrolled component, `defaultValue` is used instead.
React provides powerful abstractions that free you from touching the DOM directly in most cases, but sometimes you simply need to access the underlying API, perhaps to work with a third-party library or existing code.
## The Mock DOM
## The Virtual DOM
React is so fast because it never talks to the DOM directly. React maintains a fast in-memory representation of the DOM. `render()` methods return a *description* of the DOM, and React can diff this description with the in-memory representation to compute the fastest way to update the browser.
@@ -62,7 +62,7 @@ React.renderComponent(
## More About Refs
To learn more about refs, including ways to use them effectively, see our [more about refs](./more-about-refs.html) documentation.
To learn more about refs, including ways to use them effectively, see our [more about refs](/react/docs/more-about-refs.html) documentation.
## Component Lifecycle
@@ -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(DOMElement rootNode)` is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here.
*`componentDidMount()` 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, DOMElement rootNode)` is invoked immediately after updating occurs.
*`componentDidUpdate(object prevProps, object prevState)` is invoked immediately after updating occurs.
### Unmounting
@@ -103,12 +103,6 @@ _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
@@ -119,7 +113,7 @@ In addition to that philosophy, we've also taken the stance that we, as authors
### Polyfills Needed to Support Older Browsers
These six functions can be polyfilled using `es5-shim.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim):
`es5-shim.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim) provides the following that React needs:
*`Array.isArray`
*`Array.prototype.forEach`
@@ -127,8 +121,28 @@ These six functions can be polyfilled using `es5-shim.js` from [kriskowal's es5-
*`Array.prototype.some`
*`Date.now`
*`Function.prototype.bind`
*`Object.keys`
Other required polyfills:
`es5-sham.js`, also from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim), provides the following that React needs:
*`Object.create`– Provided by `es5-sham.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim).
*`console.*`– Only needed when using the unminified build. If you need to polyfill this, try [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).
*`Object.create`
*`Object.freeze`
The unminified build of React needs the following from [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).
*`console.*`
When using HTML5 elements in IE8 including `<section>`, `<article>`, `<nav>`, `<header>`, and `<footer>`, it's also necessary to include [html5shiv](https://github.com/aFarkas/html5shiv) or a similar script.
### 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 for.
#### 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.
Every project uses a different system for building and deploying JavaScript. We've tried to make React as environment-agnostic as possible.
@@ -38,15 +38,18 @@ If you have [npm](http://npmjs.org/), you can simply run `npm install -g react-t
### Helpful Open-Source Projects
The open-source community has built tools that integrate JSX with several build systems.
* [reactify](https://github.com/andreypopp/reactify) - use JSX with [browserify](http://browserify.org/)
* [grunt-react](https://github.com/ericclemmons/grunt-react) - [grunt](http://gruntjs.com/) task for JSX
* [require-jsx](https://github.com/seiffert/require-jsx) - use JSX with [require.js](http://requirejs.org/)
* [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/)
The open-source community has built tools that integrate JSX with several build systems. See [JSX integrations](/react/docs/complementary-tools.html#jsx-integrations) for the full list.
## React Page
### Syntax Highlighting & Linting
To get started on a new project, you can use [react-page](https://github.com/facebook/react-page/), a complete React project creator. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
* Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
* [JSX syntax highlighting](https://github.com/yungsters/sublime/blob/master/tmLanguage/JavaScript%20(JSX\).tmLanguage) is available for Sublime Text and other editors
that support `*.tmLanguage`.
* [web-mode.el](http://web-mode.org) is an autonomous emacs major mode that indents and highlights JSX
* Linting provides accurate line numbers after compiling without sourcemaps.
* Elements use standard scoping so linters can find usage of out-of-scope components.
### Debugging
[React Developer Tools](https://github.com/facebook/react-devtools) is a [Chrome extension](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) that allows you to inspect the React component hierarchy in the Chrome Developer Tools.
`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).
- [`cloneWithProps()`](clone-with-props.html), to make shallow copies of React components and change their props.
- [`update()`](update.html), a helper function that makes dealing with immutable data in JavaScript easier.
To get the add-ons, use `react-with-addons.js` (and its minified counterpart) rather than the common `react.js`.
* All of [Instagram.com](http://instagram.com/) is built on React.
* Many components on [Facebook.com](http://www.facebook.com/), including the commenting interface, ads creation flows, and page insights.
* [Khan Academy](http://khanacademy.org/) is using React for its question editor.
### Sample Code
* 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.
React provides a `ReactTransitionGroup` addon component as a low-level API for animation, and a `ReactCSSTransitionGroup` for easily implementing basic CSS animations and transitions.
## High-level API: `ReactCSSTransitionGroup`
`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.
```javascript{22-24}
/** @jsx React.DOM */
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
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.
You can use these classes to trigger a CSS animation or transition. For example, try adding this CSS and adding a new list item:
```css
.example-enter {
opacity: 0.01;
transition: opacity .5s ease-in;
}
.example-enter.example-enter-active {
opacity: 1;
}
```
You'll notice that when you try to remove an item `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:
```css
.example-leave {
opacity: 1;
transition: opacity .5s ease-in;
}
.example-leave.example-leave-active {
opacity: 0.01;
}
```
### Disabling Animations
You can disable animating `enter` or `leave` animations if you want. For example, sometimes you may want an `enter` animation and no `leave` animation, but `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.
## 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
By default `ReactTransitionGroup` renders as a `span`. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`:
```javascript{1}
<ReactTransitionGroup component={React.DOM.ul}>
...
</ReactTransitionGroup>
```
Every DOM component is under `React.DOM`. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself!
`ReactLink` is an easy way to express two-way binding with React.
> Note:
>
> If you're new to the framework, note that `ReactLink` is not needed for most applications and should be used cautiously.
In React, data flows one way: from owner to child. This is because data only flows one direction in [the Von Neumann model of computing](http://en.wikipedia.org/wiki/Von_Neumann_architecture). You can think of it as "one-way data binding."
However, there are lots of applications that require you to read some data and flow it back into your program. For example, when developing forms, you'll often want to update some React `state` when you receive user input. Or perhaps you want to perform layout in JavaScript and react to changes in some DOM element size.
In React, you would implement this by listening to a "change" event, read from your data source (usually the DOM) and call `setState()` on one of your components. "Closing the data flow loop" explicitly leads to more understandable and easier-to-maintain programs. See [our forms documentation](/react/docs/forms.html) for more information.
Two-way binding -- implicitly enforcing that some value in the DOM is always consistent with some React `state` -- is concise and supports a wide variety of applications. We've provided `ReactLink`: syntactic sugar for setting up the common data flow loop pattern described above, or "linking" some data source to React `state`.
> Note:
>
> ReactLink is just a thin wrapper and convention around the `onChange`/`setState()` pattern. It doesn't fundamentally change how data flows in your React application.
## ReactLink: Before and After
Here's a simple form example without using `ReactLink`:
This works really well and it's very clear how data is flowing, however with a lot of form fields it could get a bit verbose. Let's use `ReactLink` to save us some typing:
`LinkedStateMixin` adds a method to your React component called `linkState()`. `linkState()` returns a `ReactLink` object which contains the current value of the React state and a callback to change it.
`ReactLink` objects can be passed up and down the tree as props, so it's easy (and explicit) to set up two-way binding between a component deep in the hierarchy and state that lives higher in the hierarchy.
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.
As you can see, `ReactLink` objects are very simple objects that just have a `value` and `requestChange` prop. And `LinkedStateMixin` is similarly simple: it just populates those fields with a value from `this.state` and a callback that calls `this.setState()`.
The `valueLink` prop is also quite simple. It simply handles the `onChange` event and calls `this.props.valueLink.requestChange()` and also uses `this.props.valueLink.value` instead of `this.props.value`. That's it!
When using `classSet()`, pass an object with keys of the CSS class names you might or might not need. Truthy values will result in the key being a part of the resulting string.
`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 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`.**
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.
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.
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.
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.
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.
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.
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.
React lets you use whatever style of data management you want, including mutation. However, if you can use immutable data in performance-critical parts of your application it's easy to implement a fast `shouldComponentUpdate()` method to significantly speed up your app.
Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like [Clojure](http://clojure.org/). However, we've provided a simple immutability helper, `update()`, that makes dealing with this type of data much easier, *without* fundamentally changing how your data is represented.
## The main idea
If you mutate data like this:
```javascript
myData.x.y.z=7;
myData.a.b.push(9);
```
you have no way of determining which data has changed since the previous copy is destroyed. Instead, you need to create a new copy of `myData` and change only the parts of it that need to be changed. Then you can compare the old copy of `myData` with the new one in `shouldComponentUpdate()` using triple-equals:
```javascript
varnewData=deepCopy(myData);
newData.x.y.z=7;
newData.a.b.push(9);
```
Unfortunately, deep copies are expensive, and sometimes impossible. You can alleviate this by only copying objects that need to be changed and by reusing the objects that haven't changed. Unfortunately, in today's JavaScript this can be cumbersome:
```javascript
varnewData=extend(myData,{
x:extend(myData.x,{
y:extend(myData.x.y,{z:7}),
}),
a:extend(myData.a,{b:myData.a.b.concat(9)})
});
```
While this is fairly performant (since it only shallow copies `log n` objects and reuses the rest), it's a big pain to write. Look at all the repetition! This is not only annoying, but also provides a large surface area for bugs.
`update() provides simple syntactic sugar around this pattern to make writing this code easier. This code becomes:
```javascript
var newData = React.addons.update(myData, {
x: {y: {z: {$set: 7}}},
a: {b: {$push: [7]}}
});
```
While the syntax takes a little getting used to (though it's inspired by [MongoDB's query language](http://docs.mongodb.org/manual/core/crud-introduction/#query)) there's no redundancy, it's statically analyzable and it's not much more typing than the mutative version.
The `$`-prefixed keys are called *directives*. The data structure they are "mutating" is called the *target*.
## Available directives
* `{$push: array}` `push()` all the items in `array` on the target
* `{$unshift: array}` `unshift()` all the items in `array` on the target
* `{$splice: array of arrays}` for each item in `array()` call `splice()` on the target with the parameters provided by the item.
* `{$set: any}` replace the target entirely
* `{$merge: object}` merge the keys of `object` with the target
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).
* **[pyReact](https://github.com/facebook/react-python)** [Python](http://www.python.org/) bridge to JSX.
* **[react-rails](https://github.com/facebook/react-rails)** Ruby gem for using JSX with [Ruby on Rails](http://rubyonrails.org/).
### 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-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.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](http://andreypopp.viewdocs.io/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.
* **[react-translate-component](https://github.com/martinandert/react-translate-component)** React component for i18n.
* **[Instagram.com](http://instagram.com/)** is 100% built on React, both public site and internal tools.
* **[Facebook.com](http://www.facebook.com/)**'s commenting interface, business management tools, [Lookback video editor](http://facebook.com/lookback/edit), page insights, and most, if not all, new JS development.
* **[Khan Academy](http://khanacademy.org/)** uses React for most new JS development.
* **[Sberbank](http://sberbank.ru/moscow/ru/person/)**, Russia's number one bank, is built with React.
* **[The New York Times's 2014 Red Carpet Project](http://www.nytimes.com/interactive/2014/02/02/fashion/red-carpet-project.html?_r=0)** is built with React.
### Sample Code
* **[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 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!
* **[React server rendering example](https://github.com/mhart/react-server-example)** Demonstrates how to use React's server rendering capabilities.
@@ -28,7 +28,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
<!DOCTYPE html>
<html>
<head>
<scriptsrc="build/react.min.js"></script>
<scriptsrc="build/react.js"></script>
<scriptsrc="build/JSXTransformer.js"></script>
</head>
<body>
@@ -44,7 +44,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
</html>
```
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](/react/docs/jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
### Separate File
@@ -90,7 +90,7 @@ React.renderComponent(
> Note:
>
> The comment parser is very strict right now, in order for it to pick up the `@jsx` modifier, two conditions are required. The `@jsx` comment block must be the first comment on the file. The comment must start with `/**` (`/*` and `//` will not work). If the parser can't find the `@jsx` comment, it will output the file without transforming it.
> The comment parser is very strict right now; in order for it to pick up the `@jsx` modifier, two conditions are required. The `@jsx` comment block must be the first comment on the file. The comment must start with `/**` (`/*` and `//` will not work). If the parser can't find the `@jsx` comment, it will output the file without transforming it.
Update your HTML file as below:
@@ -99,7 +99,7 @@ Update your HTML file as below:
<html>
<head>
<title>Hello React!</title>
<script src="build/react.min.js"></script>
<script src="build/react.js"></script>
<!-- No need for JSXTransformer! -->
</head>
<body>
@@ -115,4 +115,4 @@ If you want to use React within a module system, [fork our repo](http://github.c
## Next Steps
Check out [the tutorial](tutorial.html) and the other examples in the `/examples` directory to learn more. Good luck, and welcome!
Check out [the tutorial](/react/docs/tutorial.html) and the other examples in the `/examples` directory to learn more. Good luck, and welcome!
`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.
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.
Like `React.Children.map()` but does not return an object.
#### React.Children.only
```javascript
objectReact.Children.only(objectchildren)
```
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.
@@ -31,9 +60,9 @@ Configure React's event system to handle touch events on mobile devices.
functioncreateClass(objectspecification)
```
Creates a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
Create a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
For more information about the specification object, see [Component Specs and Lifecycle](component-specs.html).
For more information about the specification object, see [Component Specs and Lifecycle](/react/docs/component-specs.html).
Renders a React component into the DOM in the supplied `container`.
Render a React component into the DOM in the supplied `container` and return a reference to the component.
If the React component was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
If the optional callback is provided, it will be executed after the component is rendered or updated.
Remove a mounted React component from the DOM and clean up its event handlers and state.
Remove a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns `true` if a component was unmounted and `false` if there was no component to unmount.
> Note:
>
> This method was called `React.unmountAndReleaseReactRootNode` until v0.5. It still works in v0.5 but will be removed in future versions.
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.
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.
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.
Component classses created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
Component classes created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
### getDOMNode
@@ -60,7 +60,7 @@ var Avatar = React.createClass({
Properties that are specified directly on the target component instance (such as `src` and `userId` in the above example) will not be overwritten by `transferPropsTo`.
@@ -107,3 +107,12 @@ If your `render()` method reads from something other than `this.props` or `this.
Calling `forceUpdate()` will cause `render()` to be called on the component and its children, but React will still only update the DOM if the markup changes.
Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your application much simpler and more efficient.
### isMounted()
```javascript
boolisMounted()
```
`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()`.
When called, it should examine `this.props` and `this.state` and return a single child component. This child component can be either a native DOM component (such as `<div>`) or another composite component that you've defined yourself.
When called, it should examine `this.props` and `this.state` and return a single child component. This child component can be either a virtual representation of a native DOM component (such as `<div />` or `React.DOM.div()`) or another composite component that you've defined yourself.
The `render()` function should be *pure*, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using `setTimeout`). If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes server rendering more practical and makes components easier to think about.
@@ -31,7 +31,7 @@ The `render()` function should be *pure*, meaning that it does not modify compon
objectgetInitialState()
```
Invoked once when the component is mounted. The return value will be used as the initial value of `this.state`.
Invoked once before the component is mounted. The return value will be used as the initial value of `this.state`.
### getDefaultProps
@@ -51,7 +51,7 @@ This method is invoked before `getInitialState` and therefore cannot rely on `th
objectpropTypes
```
The `propTypes` object allows you to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](reusable-components.html).
The `propTypes` object allows you to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html).
<!-- TODO: Document propTypes here directly. -->
@@ -62,11 +62,45 @@ The `propTypes` object allows you to validate props being passed to your compone
arraymixins
```
The `mixins` array allows you to use mixins to share behavior among multiple components. For more information about mixins, see [Reusable Components](reusable-components.html).
The `mixins` array allows you to use mixins to share behavior among multiple components. For more information about mixins, see [Reusable Components](/react/docs/reusable-components.html).
<!-- TODO: Document mixins here directly. -->
### statics
```javascript
objectstatics
```
The `statics` object allows you to define static methods that can be called on the component class. For example:
```javascript
varMyComponent=React.createClass({
statics:{
customMethod:function(foo){
returnfoo==='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
stringdisplayName
```
The `displayName` string is used in debugging messages. JSX sets this value automatically, see [JSX in Depth](/react/docs/jsx-in-depth.html#react-composite-components).
## Lifecycle Methods
Various methods are executed at specific points in a component's lifecycle.
@@ -78,19 +112,23 @@ Various methods are executed at specific points in a component's lifecycle.
componentWillMount()
```
Invoked immediately before rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change.
Invoked once, immediately before the initial rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change.
### Mounting: componentDidMount
```javascript
componentDidMount(DOMElementrootNode)
componentDidMount()
```
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()`.
Invoked immediately after rendering occurs. At this point in the lifecycle, the component has a DOM representation which you can access via `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.9, 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
@@ -157,13 +195,17 @@ Use this as an opportunity to perform preparation before an update occurs.
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.9, 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()`.
React attempts to support all common elements. If you need an element that isn't listed here, please file an issue.
The following elements are supported:
### HTML Elements
The following HTML elements are supported:
```
a abbr address area article aside audio b base bdi bdo big blockquote body br
button canvas caption cite code col colgroup data datalist dd del details dfn
@@ -29,37 +28,50 @@ thead time title tr track u ul var video wbr
### SVG elements
The following SVG elements are supported:
```
circle g line path polyline rect svg text
circle defs g line linearGradient path polygon polyline radialGradient rect
stop svg text
```
You may also be interested in [react-art](https://github.com/facebook/react-art), a drawing library for React that can render to Canvas, SVG, or VML (for IE8).
## Supported Attributes
React supports all `data-*` and `aria-*` attributes as well as every attribute
in the following lists. Note that all attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
React supports all `data-*` and `aria-*` attributes as well as every attribute in the following lists.
For a list of events, see [Supported Events](events.html).
> Note:
>
> All attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
For a list of events, see [Supported Events](/react/docs/events.html).
### HTML Attributes
These standard attributes are supported:
```
accessKey accept action ajaxify allowFullScreen allowTransparency alt
accept accessKey action allowFullScreen allowTransparency alt async
style tabIndex target title type value width wmode
```
In addition, the non-standard `autoCapitalize` attribute is supported for Mobile Safari.
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.
### SVG Attributes
```
cx cy d fill fx fy points r stroke strokeLinecap strokeWidth transform x x1 x2
version viewBox y y1 y2 spreadMethod offset stopColor stopOpacity
gradientUnits gradientTransform
cx cy d fill fx fy gradientTransform gradientUnits offset points r rx ry
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.
* 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.
* The `style` attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM `style` JavaScript property, is more efficient, and prevents XSS security holes.
* All event objects conform to the W3C spec, and all events (including submit) bubble correctly per the W3C spec. See [Event System](events.html) for more details.
* The `onChange` event behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time. See [Forms](forms.html) for more details.
* All event objects conform to the W3C spec, and all events (including submit) bubble correctly per the W3C spec. See [Event System](/react/docs/events.html) for more details.
* The `onChange` event behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time. See [Forms](/react/docs/forms.html) for more details.
* Form input attributes such as `value` and `checked`, as well as `textarea`. [More here](/react/docs/forms.html).
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.
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.
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: <divid="before"/>
renderB: <divid="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.
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.
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.
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.
This was originally a [blog post](/react/blog/2013/11/05/thinking-in-react.html) from the [official React blog](/react/blog).
React is, in my opinion, the premier way to build big, fast Web apps with JavaScript. It's scaled very well for us at Facebook and Instagram.
One of the many great parts of React is how it makes you think about apps as you build them. In this post I'll walk you through the thought process of building a searchable product data table using React.
## Start with a mock
Imagine that we already have a JSON API and a mock from our designer. Our designer apparently isn't very good because the mock looks like this:
## Step 1: break the UI into a component hierarchy
The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you're working with a designer they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!
But how do you know what should be its own component? Just use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing it should be decomposed into smaller subcomponents.
Since you're often displaying a JSON data model to a user, you'll find that if your model was built correctly your UI (and therefore your component structure) will map nicely onto it. That's because user interfaces and data models tend to adhere to the same *information architecture* which means the work of separating your UI into components is often trivial. Just break it up into components that represent exactly one piece of your data model.
You'll see here that we have five components in our simple app. I've italicized the data each component represents.
1.**`FilterableProductTable` (orange):** contains the entirety of the example
2.**`SearchBar` (blue):** receives all *user input*
3.**`ProductTable` (green):** displays and filters the *data collection* based on *user input*
4.**`ProductCategoryRow` (turquoise):** displays a heading for each *category*
5.**`ProductRow` (red):** displays a row for each *product*
If you look at `ProductTable` you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference and there's an argument to be made either way. For this example I left it as part of `ProductTable` because it is part of rendering the *data collection* which is `ProductTable`'s responsibility. However if this header grows to be complex (i.e. if we were to add affordances for sorting) it would certainly make sense to make this its own `ProductTableHeader` component.
Now that we've identified the components in our mock, let's arrange them into a hierarchy. This is easy. Components that appear within another component in the mock should appear as a child in the hierarchy:
Now that you have your component hierarchy it's time to start implementing your app. The easiest way is to build a version that takes your data model and renders the UI but has no interactivity. It's easiest to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing. We'll see why.
To build a static version of your app that renders your data model you'll want to build components that reuse other components and pass data using *props*. *props* are a way of passing data from parent to child. If you're familiar with the concept of *state*, **don't use state at all** to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app you don't need it.
You can build top-down or bottom-up. That is, you can either start with building the components higher up in the hierarchy (i.e. starting with `FilterableProductTable`) or with the ones lower in it (`ProductRow`). In simpler examples it's usually easier to go top-down and on larger projects it's easier to go bottom-up and write tests as you build.
At the end of this step you'll have a library of reusable components that render your data model. The components will only have `render()` methods since this is a static version of your app. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. If you make a change to your underlying data model and call `renderComponent()` again the UI will be updated. It's easy to see how your UI is updated and where to make changes since there's nothing complicated going on since React's **one-way data flow** (also called *one-way binding*) keeps everything modular, easy to reason about, and fast.
Simply refer to the [React docs](http://facebook.github.io/react/docs/) if you need help executing this step.
### A brief interlude: props vs state
There are two types of "model" data in React: props and state. It's important to understand the distinction between the two; skim [the official React docs](http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html) if you aren't sure what the difference is.
## Step 3: Identify the minimal (but complete) representation of UI state
To make your UI interactive you need to be able to trigger changes to your underlying data model. React makes this easy with **state**.
To build your app correctly you first need to think of the minimal set of mutable state that your app needs. The key here is DRY: *Don't Repeat Yourself*. Figure out what the absolute minimal representation of the state of your application needs to be and compute everything else you need on-demand. For example, if you're building a TODO list, just keep an array of the TODO items around; don't keep a separate state variable for the count. Instead, when you want to render the TODO count simply take the length of the TODO items array.
Think of all of the pieces of data in our example application. We have:
* The original list of products
* The search text the user has entered
* The value of the checkbox
* The filtered list of products
Let's go through each one and figure out which one is state. Simply ask three questions about each piece of data:
1. Is it passed in from a parent via props? If so, it probably isn't state.
2. Does it change over time? If not, it probably isn't state.
3. Can you compute it based on any other state or props in your component? If so, it's not state.
The original list of products is passed in as props, so that's not state. The search text and the checkbox seem to be state since they change over time and can't be computed from anything. And finally, the filtered list of products isn't state because it can be computed by combining the original list of products with the search text and value of the checkbox.
OK, so we've identified what the minimal set of app state is. Next we need to identify which component mutates, or *owns*, this state.
Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. **This is often the most challenging part for newcomers to understand,** so follow these steps to figure it out:
For each piece of state in your application:
* Identify every component that renders something based on that state.
* Find a common owner component (a single component above all the components that need the state in the hierarchy).
* Either the common owner or another component higher up in the hierarchy should own the state.
* If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.
Let's run through this strategy for our application:
*`ProductTable` needs to filter the product list based on state and `SearchBar` needs to display the search text and checked state.
* The common owner component is `FilterableProductTable`.
* It conceptually makes sense for the filter text and checked value to live in `FilterableProductTable`
Cool, so we've decided that our state lives in `FilterableProductTable`. First, add a `getInitialState()` method to `FilterableProductTable` that returns `{filterText: '', inStockOnly: false}` to reflect the initial state of your application. Then pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as a prop. Finally, use these props to filter the rows in `ProductTable` and set the values of the form fields in `SearchBar`.
You can start seeing how your application will behave: set `filterText` to `"ball"` and refresh your app. You'll see the data table is updated correctly.
So far we've built an app that renders correctly as a function of props and state flowing down the hierarchy. Now it's time to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
React makes this data flow explicit to make it easy to understand how your program works, but it does require a little more typing than traditional two-way data binding. React provides an add-on called `ReactLink` to make this pattern as convenient as two-way binding, but for the purpose of this post we'll keep everything explicit.
If you try to type or check the box in the current version of the example you'll see that React ignores your input. This is intentional, as we've set the `value` prop of the `input` to always be equal to the `state` passed in from `FilterableProductTable`.
Let's think about what we want to happen. We want to make sure that whenever the user changes the form we update the state to reflect the user input. Since components should only update their own state, `FilterableProductTable` will pass a callback to `SearchBar` that will fire whenever the state should be updated. We can use the `onChange` event on the inputs to be notified of it. And the callback passed by `FilterableProductTable` will call `setState()` and the app will be updated.
Though this sounds like a lot it's really just a few lines of code. And it's really explicit how your data is flowing throughout the app.
## And that's it
Hopefully this gives you an idea of how to think about building components and applications with React. While it may be a little more typing than you're used to, remember that code is read far more than it's written, and it's extremely easy to read this modular, explicit code. As you start to build large libraries of components you'll appreciate this explicitness and modularity, and with code reuse your lines of code will start to shrink :)
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 be building a simple, but realistic comments box that you can drop into a blog, a basic version of the realtime comments offered by Disqus, LiveFyre or Facebook comments.
We'll provide:
@@ -32,6 +35,7 @@ For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your fav
@@ -39,6 +43,7 @@ For this tutorial we'll use prebuilt JavaScript files on a CDN. Open up your fav
/**
* @jsx React.DOM
*/
// The above declaration must remain intact at the top of the script.
// Your code here
</script>
</body>
@@ -65,7 +70,7 @@ Let's build the `CommentBox` component, which is just a simple `<div>`:
varCommentBox=React.createClass({
render:function(){
return(
<divclass="commentBox">
<divclassName="commentBox">
Hello,world!IamaCommentBox.
</div>
);
@@ -99,7 +104,7 @@ React.renderComponent(
);
```
Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](jsx-in-depth.html).
Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](/react/docs/jsx-in-depth.html).
#### What's going on
@@ -120,7 +125,7 @@ Let's build skeletons for `CommentList` and `CommentForm` which will, again, be
varCommentList=React.createClass({
render:function(){
return(
<divclass="commentList">
<divclassName="commentList">
Hello,world!IamaCommentList.
</div>
);
@@ -130,7 +135,7 @@ var CommentList = React.createClass({
varCommentForm=React.createClass({
render:function(){
return(
<divclass="commentForm">
<divclassName="commentForm">
Hello,world!IamaCommentForm.
</div>
);
@@ -145,7 +150,7 @@ Next, update the `CommentBox` component to use its new friends:
var CommentBox = React.createClass({
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList />
<CommentForm />
@@ -166,7 +171,7 @@ Let's create our third component, `Comment`. We will want to pass it the author
var CommentList = React.createClass({
render: function() {
return (
<div class="commentList">
<div className="commentList">
<Comment author="Pete Hunt">This is one comment</Comment>
<Comment author="Jordan Walke">This is *another* comment</Comment>
</div>
@@ -186,8 +191,8 @@ Let's create the Comment component. It will read the data passed to it from the
var Comment = React.createClass({
render: function() {
return (
<div class="comment">
<h2 class="commentAuthor">
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
@@ -205,12 +210,13 @@ 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):
Let's replace the hard-coded data with some dynamic data from the server. We will remove the data prop and replace it with a URL to fetch:
```javascript{2}
```javascript{3}
// tutorial11.js
React.renderComponent(
<CommentBox url="comments.json" />,
@@ -346,7 +352,7 @@ var CommentBox = React.createClass({
},
render: function() {
return (
<div class="commentBox">
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
@@ -369,27 +375,31 @@ When the component is first created, we want to GET some JSON from the server an
]
```
We will use jQuery 1.5 to help make an asynchronous request to the server.
We'll use jQuery to help make an asynchronous request to the server.
Note: because this is becoming an AJAX application you'll need to develop your app using a web server rather than as a file sitting on your file system. The easiest way to do this is to run `python -m SimpleHTTPServer` in your application's directory.
@@ -399,16 +409,15 @@ var CommentBox = React.createClass({
});
```
The key is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is trivial to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
Here, `componentWillMount` is a method called automatically by React before a component is rendered. The key to dynamic updates is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is only a minor change to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
```javascript{3,17-21,35}
```javascript{3,16-17,31}
// tutorial14.js
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -419,14 +428,11 @@ var CommentBox = React.createClass({
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 5 seconds after that. Try running this in your browser and changing the `comments.json` file; within 5 seconds, the changes will show!
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 2 seconds after that. Try running this in your browser and changing the `comments.json` file; within 2 seconds, the changes will show!
### Adding new comments
@@ -453,10 +459,10 @@ Now it's time to build the form. Our `CommentForm` component should ask the user
@@ -465,7 +471,7 @@ var CommentForm = React.createClass({
Let's make the form interactive. When the user submits the form, we should clear it, submit a request to the server, and refresh the list of comments. To start, let's listen for the form's submit event and clear it.
```javascript{3-13,16,21}
```javascript{3-13,16-17,21}
// tutorial16.js
var CommentForm = React.createClass({
handleSubmit: function() {
@@ -481,14 +487,14 @@ var CommentForm = React.createClass({
@@ -634,14 +632,13 @@ var CommentBox = React.createClass({
Our application is now feature complete but it feels slow to have to wait for the request to complete before your comment appears in the list. We can optimistically add this comment to the list to make the app feel faster.
```javascript{14-16}
```javascript{13-15}
// tutorial20.js
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -649,13 +646,13 @@ var CommentBox = React.createClass({
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
comments.push(comment);
this.setState({data: comments});
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
data: comment,
dataType: 'json',
mimeType: 'textPlain',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this)
@@ -666,14 +663,11 @@ var CommentBox = React.createClass({
@@ -687,4 +681,4 @@ var CommentBox = React.createClass({
### Congrats!
You have just built a comment box in a few simple steps. Learn more about [why to use React](why-react.html), or dive into the [API reference](top-level-api.html) and start hacking! Good luck!
You have just built a comment box in a few simple steps. Learn more about [why to use React](/react/docs/why-react.html), or dive into the [API reference](/react/docs/top-level-api.html) and start hacking! Good luck!
"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.
Download the starter kit to get everything you need to
[get started with React](/react/docs/getting-started.html).
[get started with React](/react/docs/getting-started.html). The starter kit includes React, the in-browser JSX transformer, and some simple example apps.
@@ -12,40 +12,72 @@ 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.
All scripts are also available via [CDNJS](http://cdnjs.com/#react).
All scripts are also available via [CDNJS](http://cdnjs.com/libraries/react/).
## npm
To install the JSX transformer on your computer, run:
```sh
$ npm install -g react-tools
```
For more info about the `jsx` binary, see the [Getting Started](/react/docs/getting-started.html#offline-transform) guide.
If you're using an npm-compatible packaging system like browserify or webpack, you can use the `react` package. After installing it using `npm install react` or adding `react` to `package.json`, you can use React:
```js
varReact=require('react');
React.renderComponent(...);
```
If you'd like to use any [add-ons](/react/docs/addons.html), use `var React = require('react/addons');` instead.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.