ReactTools is deprecated, it doesn't belong at the root of the project. We'll remove it after 0.14 but for now this moves it so that it's contained and not intermixed with the rest of the project. The currect behavior of copying src/ into the package is maintained.
This ensures that we can consume code from npm that has our process.env pattern. Unfortunately we'll run the same transform on minified builds but it's pretty quick.
This reworks a few things in building and distributing React. The biggest change is using fbjs to share dependencies with other libraries. We're also using Gulp for some build steps.
With this, ReactMultiChild handles all of the children-related operations for ReactDOMComponent so that we don't process operations out of order. This is necessary because ReactMultiChild does its own batching so there's no way without its cooperation to get the timing right here.
Ideally we'll factor this logic out a bit better in subsequent updates but this is the simplest way to fix#1232 which has embarrassingly been open for over a year.
I'm proposing these changes because I found some repetition / lack of
clarity and some language that suggested that you could mutate
`this.state` directly.
Rely on jest for now until we get a better and less hacky solution to running tests in the browser, probably a totally different test suite with different behavior/goals.
I came across an issue on a React project where I needed to programatically set the default value of an input as the result of an async call. (I was prepopulating a zip code field from the Google Maps Geocoding API). It didn't work when I passed in an updated defaultValue prop, until I came across this StackOverflow: http://stackoverflow.com/questions/30146105/react-input-defaultvalue-doesnt-update-with-state. I was able to get it to do what I wanted by passing in the value prop instead.
The addons module warning is currently causing issues with babel/JSPM due to the warning message getting parsed as a require statement. Adding a break using string concatenation appears to prevent any issues.
Example error using JSPM:
```
Error loading "react-addons-{addon}" from...
```
- Add missing object-assign dependency
- Add batchedUpdates to ReactDOMClient, rename the two addons to `unstable_`
- Delete react/addons/* (leaving react/addons with a slightly updated warning)
- Add README.md, LICENSE, PATENTS to each addons package
Changes:
- moves after_script to script
- adds `set -e`
- creates a seperate matrix 'build'
Way at the bottom of the travis output:
```
1571: curl: (26) couldn't open file "build/react.tgz"
```
This seems to be broken since 12c9fee94e
No reason to limit at 100. I can't imagine a reasonable tree with depth over 10,000 but that should still be small enough to "catch infinite loops" quickly.
This hack allow us to get rid of the stateful module ReactLifeCycle since
we can infer the value of isMounted even without it. This gets rid of
the try/catch which is deopting all mountComponent calls.
As a next step we could deprecate isMounted completely and avoid stateful
APIs. Since it can be easily simulated if you truly need it.
Since I fixed the server-side rendering it is now possible to trigger these
callbacks on the client alone. They will still be queued up on the server
but they are never executed.
This allows updates to be enqueued during render. setState in
componentWillMount will still be collected as part of the first pass so
if nothing else get added as pending, they won't trigger a second rerender.
This allow us to get rid of one more stateful special case.
This simply ignores any enqueued actions. This means that we don't have to have special logic for componentWillMount. It is just that those updates are never enqueued.
This was used for any invariant that was subsequently removed. It turns
out that this is completely unnecessary now. Any setState calls will
enqueue and update and the component added to the update queue. However,
since the pending fields are reset after componentWillUnmount, any update
will still be ignored.
It was impossible to get here because if you enqueue something
Also ensure that they're only used in DEV because we will be reading
state that is DEV only here.
This should only be used for tracking string refs. For that purpose, we
need a single central stateful module that is coupled to createElement.
Which is why it needs to live in isomorphic.
Eventually this will go away completely.
This decouples the stateful imperative API from the class creation.
Instead, they get injected into the class from the renderer. Stateful
modules should always be injected.
As a convenience, just like props/context/refs, we set it up after
construction using mutation. That way it is optional to pass it along
the super call constructor chain.
We won't be able to support this after DOM-components-as-refs but we don't expect many people to be passing DOM components to this function anyway, and it should be fairly straightforward for people to clean up failing unit tests using this function.
(This module also isn't public API and never has been.)
We won't be able to support this after DOM-components-as-refs but we don't expect many people to be passing DOM components to this function anyway, and it should be fairly straightforward for people to clean up failing unit tests using this function.
Squashed commit:
[4564e55] Ensures we don't need to update this page for every release.
[b0d60f9] update script sources to be even with the example file in reactjs/react-tutorial repo
This is kind of a confusing place for it but it is intimitely tied to the
update life cycle which is what the update queue is about.
This kills some dependencies from isomorphic to the renderer.
We keep track of the fact that something is rendering for a bunch of
warnings. (ReactCurrentOwner.current !== null)
Once we get rid of owner for string refs, I'll convert those to something
like "isRendering" instead. The interesting part is that feature `__DEV__`
only. It is only used for warnings. Except for this case.
This means that we can get rid of the special case for the isRendering
stack on in prod.
- babel-eslint ^3.1.14 fixesbabel/babel-eslint#120
- babel updated from ^5.3.3 to ^3.5.5, which changes stuff, I guess
- eslint updated from ^0.21.2 to ^0.22.1, which makes `no-shadow` also
check class declarations
In xml node name casing is exactly the same as the node was originally named.
Make sure to convert node and tag names to lower case before making any node
and tag name checks.
Fixes#3960.
spicyj noticed newer versions of babel-eslint seemed not to error on
no-unused-vars, and I was able to repro. It seems like something broke
between 3.1.9 and 3.1.10. (Smaller repro case and babel-eslint bug
report to come)
His commit failed on travis, but not on his local machine:
https://travis-ci.org/facebook/react/jobs/65468729
> The two callers of this function have different warning configs
> internally (static_upstream/core/createWarning.js) so we can't sync it
> like this without changing behavior. We should just split this out
> into two separate warning calls probably – this code is a little
> overabstracted.
https://github.com/facebook/react/pull/4021#discussion_r31690020
@spicyj
I think completely removing warnAndMonitorForKeyUse is a bit difficult, without
duplicating a ton of code. This at least ensures that the format string passed
to `warning` is unique. Plus, because the FB internal code in question only
matches the beginning of the format string, I think there should be zero
internal changes that need to be made to support this refactor.
The `warning` implementation checked that the message is long enough to
be useful. See commit f5038829d for more information.
It makes more sense to move this into a lint rule, and also to apply it
for both `warning` and `invariant`. We can safely remove stuff from the
`warning` implementation as we replace the function internally anyways.
https://github.com/facebook/react/pull/4021#issuecomment-108694976
@spicyj
The wording for an incorrect number of arguments based on counting %s
substitutions. The previous wording was backwards and a bit yoda-like
leading to possible ambiguity.
This should contain all the rules we probably want to use, except
react/wrap-multilines, which requires a larger codemod, and would
clutter this commit.
See #2869
Checks that the *second* argument of warning and invariant are a literal
string, or a concatination of literal strings, and that the number of
arguments is correct based on the number of %s substrings.
This commit also fixes a few places where the existing code had broken
error messages!
The rule itself is pretty straightforward, although adding the tests
ended up being a bit painful, as eslint-tester depends on mocha, and
therefore needs to be run in a separate grunt task.
This is a machine-generated codemod, but it's pretty safe since it was
generated by hooking into eslint's own report.
A few files had to be touched up by hand because there were existing
formatting issues with nested arrays/objects:
src/shared/utils/__tests__/OrderedMap-test.js
src/shared/utils/__tests__/Transaction-test.js
src/shared/utils/__tests__/traverseAllChildren-test.js
src/isomorphic/children/__tests__/ReactChildren-test.js
Introducing: a really lame version of composite components, right inside of ReactDOMComponent!
Now ReactDOMInput isn't an actual component. This brings us closer to exposing DOM nodes as refs.
Closes#3971.
> After #3968, the next thing we should do is start linting our tests.
> Historically we've ignored them due to lack of parser compatibility.
> But that shouldn't be a problem anymore. We may want to integrate
> https://www.npmjs.com/package/eslint-plugin-react to more aggressively
> lint our JSX in tests.
I understand this diff touches a lot of stuff, so I tried to keep it to
a near-minimal set of changes to make eslint happy.
- Removes esprima-fb dependency
- Tightens up eslintrc with some minor rules we were pretty-much
following anyways.
- Adds pretty colors to the `grunt lint` output
- Breaks block-scoped-var :(
Follow-up to #3963. (Returning an Error wasn't useful; it just caused a later error when actually using it because type checkers need to be functions.)
Chrome allowed some of these to be 'null' (allow `node.challenge` etc),
but FF didn't work. This will tell React to use node.setAttribute() to
set these values.
Tested in FF, Chrome, Safari. <keygen> isn't supported on IE.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen
The code sample in tip 18 in the docs contained a call to the
.getDOMNode() method which has been deprecated. The method call was
replaced with a call to React.findDOMNode(), which is the preferred way
of getting DOM nodes from a ref.
This heuristic isn't great because it relies on inspecting deep children which aren't guaranteed to be React elements. In particular, this was causing stack overflows in a component we had that used a *DOM node* as children, like `<DOMContainer>{node}</DOMContainer>`.
This reverts commits:
0a3aa8493a64c9d9d7620c58f4f6b18cf226e442086636747f
The new folder structure is organized around major packages that are expected to ship separately in some form.
`/isomorphic`
I moved classic/modern and children utils into a directory called "isomorphic" with the main export being ReactIsomorphic. This will eventually become the "react" package.
This includes all the dependencies that you might need to create a component without dependencies on the renderer/reconciler.
The rest moves into decoupled renderers.
`/renderers/dom/client` - This is the main renderer for DOM.
`/renderers/dom/server` - This is the server-side renderer for HTML strings.
`/addons` and `/test` - Same as before for now.
You're not supposed to take on a dependency inside another package.
Shared code is organized into a "shared" directory which is intended to support all the packages in that subdirectory. Meaning that once we swap to CommonJS modules, the only time you should use `..` is to target `../shared/` or `../../shared`.
E.g. `/shared/` is common utils that are used by everything.
`/renderers/shared/` is code that is shared by all renderers, such as the main reconciliation algorithm.
Shared code will likely be copied into each package rather than referenced. This allow us to have separate state and allow inlining and deadcode elimination.
Size comparison:
```
raw gz Compared to master @ 6ed98ec0c8
= = build/JSXTransformer.js
-15736 -3247 build/react-with-addons.js
+287 +7 build/react-with-addons.min.js
-14412 -2887 build/react.js
+274 +15 build/react.min.js
```
Differences mostly look to be various bits of whitespace that Babel ends up removing during its transforms (https://gist.github.com/spicyj/21ef31f4d95fb7a58daf). In minified files, mostly additions of `"use strict";`.
My old code here didn't work properly -- for a string child, getIteratorFn would return an iterator that gave each character as its own string, and we'd attempt to loop over that too.
Tests now work in Chrome again.
Also when reusing elements in multiple contexts -- before we were mutating each element to indicate its validity; now we mutate the array containing it (which we create, in the case of rest-arg children).
Fixes#2496. Fixes#3348.
Updated documentation to reflect that using React.cloneElement is the new way to copy an element and preserve `key` and `ref`.
Fixes#3432, closes#3447.
Update links to use https:// where it is supported. There's probably a lot
more that could be fixed, but these are the core ones I found (especially
the download links in order to prevent MITM attacks). Note that there are
some fb.me links that will redirect to http:// even while accessed over
https://, but this seemed like the best way to fix those for now.
NOTE: Only non-third-party files were modified. There are references to
http:// URLs in vendored/third-party files, but seems appropriate to fix
upstream for those rather than editing the files.
Also, copy one image locally to the blog, as it was hotlinking to a site
that did not support https://.
Last, use youtube-nocookie.com instead of youtube.com for video embeds,
as the former doesn't try to set a cookie on load (privacy enhancement).
I'm not super attached to this, but this feels cleaner to me. Might even be faster since flattenChildren doesn't use the index. Probably no change though.
If there are no listeners for `onSelect` yet, do not extract events. This way we can avoid issues where listeners have been set up for some event dependencies for `SelectEventPlugin`, but not all.
For instance, if `topMouseDown` has been registered but not `topMouseUp`, event extraction will set the `mouseDown` flag to true but never unset it. This leads to bugs when `onSelect` is registered and should be firing during normal key behavior. Since no `topMouseUp` has yet occurred to unset the flag, `onSelect` fails to fire.
When the style property existed, but was set to null, `this._previousStyleCopy`
was not set back to `null` causing an old value to persist. This broke setting
the style to `null` the next time.
Fixes#3606.
As far as I can tell, this is almost equivalent and is simpler. When a component's componentDidMount is called, all the listeners for that subtree will have been attached which I think is all that matters.
All testes successfully completed.
- for-in in browsers is slow, i replaced him by Object.keys + for(array)
- simple check of lengths let us not iterate if not same
- now we dont need to test for B's keys missing from A, because if length's is same and prev check success - objB hasn't more keys
- micro optimize: calling objB.hasOwnProperty
- micro optimize: replaced !objA || !obj for more speedy check === null
#inspiredby https://github.com/jurassix/react-immutable-render-mixin/pull/4
$REACT_WEBSITE_BRANCH in https://travis-ci.org/facebook/react/settings/env_vars now needs to point to the stable branch (currently 0.13-stable). I haven't tested the commit-and-push part of this but everything else works so I'm hopeful.
I ended up needing to add this attribute to work around a common IE bug, that clicking on a scrollbar gives focus to the scroll container. I needed to set it as MUST_USE_ATTRIBUTE or the attribute would not be passed through by React successfully.
remove trailing spaces
The current documentation states that the `<select>` tag supports `defaultChecked`, but it actually doesn't. I believe this documentation was meant to be written in the proposed order.
Non-working fiddle using `defaultChecked`: http://jsfiddle.net/jqs1hsLr/1/
Working fiddle using `defaultValue`: http://jsfiddle.net/nv7z0yzL/1/
Turns out lots of people write invalid HTML all the time and no one, including your browser or React, cares. Most invalid HTML combinations don't cause magic reparented nodes; only some do. The HTML5 parsing spec (https://html.spec.whatwg.org/multipage/syntax.html) specifies which tag combinations cause strange parsing behavior. I did my best to encode the logic here. It's more lenient than before in some cases, but more strict in others (before we didn't look at the whole stack of tags; now we warn with deeply nested `p` or `form` or `a` tags).
Rendering to `document.body` in the examples is conveniently short, but it can
be misleading at the same time, especially for newcomers.
While it's possible to render React components to `document.body`, any 3rd
party scripts can also mess up with it, and it can have unintended consequences
and be source of difficult-to-trace bugs.
Now that #1169 is fixed, the only thing this is used for is to determine whether `onTouchTap` causes touch listeners to be added. The only internal uses of TapEventPlugin are where touch events are already initialized (so this doesn't make a difference) and we don't support `onTouchTap` as part of the public API so this should be safe.
This reverts an early commit that made it so that elements from two
different owner in the same slot wouldn't share state.
That behavior was helpful, and we did hit a case which was solved by this.
However, this pattern is extremely uncommon. I've yet to even find the
original case, let alone any existing cases in our codebase.
Therefore, we're dropping this to simplify elements and enable new
optimizations.
We currently override a couple DOM components. We need to ensure everything we
override is still treated as a DOM component, even if it has a composite
component wrapper.
_mountImageIntoNode moved into ReactMount and wasn't being counted where it was supposed to be. In addition, all DOM elements are now wrapped in a composite wrapper but for the perf tools we want to skip over those or else we'll double-count (at least with the current accounting -- and that's effectively what we did before so this brings us back up to parity).
Fixes#3407.
Test Plan:
Used the jsbin from #3407 and saw similar output from this branch and 0.12:

$TRAVIS_COMMIT_RANGE was broken but it seems what we're doing is worse and
resulting in false negatives.
The result of the bad range was that we weren't running lint or tests for
things we should have been. It actually looks like $TRAVIS_COMMIT has been
wrong and it's not clear why this has been working at all.
ReactDOMComponent maintains a copy of the previous style
object to support in-place mutations of props.style.
This cached object was not cleared when the style
property was removed in a props update.
Fixes#3409
There is an exception when value or defaultValue is set but there are no
children as ReactDOMSelect tries to mark the first children as selected
even if there are no children.
I mis-parsed 'shallow copies' as adjective noun, instead of as a compound verb. I've adjusted the text to make it easier to parse on the first read, which should also help ESL learners to be able to parse it easier.
Summary:
Right now, if a component specifies a propType as, for example,
`myProp: React.PropTypes.shape`, without an actual shape
parameter, any prop type will be accepted, because
`React.PropTypes.shape` returns a function (the actual validator),
not an Error, currently indicating that propType checking passed.
This can create an unfortunate situation where a component looks
like it has fully specified `propTypes`, but in fact does not.
This commit addresses this by warning if a propType checker returns
anything non-falsy that is not an Error (currently all the library
PropTypes return null or an Error).
Test Plan:
Added a unit test; ran `jest` in the root repo directory.
Also ran `grunt lint` and `grunt test`
If either argument is not an object and unequal, then shallowEqual should return false.
If only one argument is an object, then shallowEqual should return false.
Fixes#3369
This is in response to #3207 to address concerns regarding third-party
scripts and browser plugins potentially altering DOM nodes within
document.body, causing problems with reconciliation.
Closes#3211.
Console is undefined in earlier versions of IE when it is not open. This causes an uncaught exception, and breaks applications in these versions of IE when attempting to warn when the console is closed.
Admittedly, console will usually be open when testing in development, but still React should not break the application when it is not.
Without this, transitioning from `<div onClick={null} />` to `<div />` triggered `willDeleteListener` to delete the `click` handler which caused problems; now, we only call `putListener` and `deleteListener` when we have an actual listener.
I now also clean up the `onClickListeners` map upon deletion and don't double-listen when updating the event listener.
* 'master' of https://github.com/facebook/react: (30 commits)
Expose --target flag on jsx executable
Contributing: cleanup quote style
Add Relay blog post
Fix long lines in vendor/fbtransform/visitors
lint vendor/*.js
fix .eslintignore
remove ballmer example
Fix a doc. cloneWithProps clones a ReactElement.
lint from root
Fixed mistake in jsdocs types for cloneWithProps
Put deprecation warning for classSet
Lint vendor/fbtransform as well
More warnings to ReactFragment.create
Warn when using constructor function directly
Move option parsing into react-tools proper.
Remove lodash devDependency
Added the immutability talk to the React.js Conf update.
Use same pathways for browser transforms as we use in react-tools
lint: remove spaces from array brackets
lint: remove spaces from object braces
...
When animating the max-height property in Safari, entering the leave state would trigger an animation to `max-height: 0`. Then when the active state kicked in, it would jump and didn't really look right. Moving the `transition` css property to the active version fixed the issue for me and worked on Safari, Chrome and Firefox. Unfortunately I'm not in a position to test in IE at the moment, but I'll do that at my first convenience tomorrow.
Fixes#1297.
onMouseEnter and onMouseLeave shouldn't *actually* use direct dispatch, but doing so is more useful than doing nothing (and I don't think it precludes adding proper enter/leave dispatching later, either).
Test Plan:
grunt test
If several children complete leaving before rendering TransitionGroup,
only the last one was removed. This could easily happen if
callback in componentWillLeave is called synchronously and several items
are removed from array. The other case is when ReactCSSTransitionGroup
has transitionLeave={false} and array is also cleaned up.
The bug was happening because this.state.children was used as a base for
children removal and it wasn't updated until the render, so only the last
removal was actually happening.
Fix involves keeping the updated children state between invocations of
_handleDoneLeaving. After updating this.state and rendering,
updatedState is cleaned up and ready for subsequent array modifications.
Test case included.
2014-11-17 15:15:54 -08:00
565 changed files with 37327 additions and 28321 deletions
*`es3` restores the previous default behavior. An additional transform is added here to ensure the use of reserved words as properties is safe (eg `this.static` will become `this['static']` for IE8 compatibility).
* The transform for the call spread operator has also been enabled.
### JSXTransformer
#### Breaking Changes
* The return value of `transform` now contains `sourceMap` as a JS object already, not an instance of `SourceMapGenerator`.
React is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on [facebook.com](https://www.facebook.com). We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and preempts some questions you may have.
React is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on [facebook.com](https://www.facebook.com). We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and answers some questions that you may have.
## [Code of Conduct](https://code.facebook.com/codeofconduct)
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated.
## Our Development Process
@@ -23,11 +27,11 @@ The core team will be monitoring for pull requests. When we get one, we'll run s
5. Make sure your code lints (`grunt lint`) - we've done our best to make sure these rules match our internal linting guidelines.
6. If you haven't already, complete the CLA.
### Contributor License Agreement ("CLA")
### Contributor License Agreement (CLA)
In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, just let us know that you have completed the CLA and we can cross-check with your GitHub username.
[Complete your CLA here](https://code.facebook.com/cla)
[Complete your CLA here.](https://code.facebook.com/cla)
## Bugs
@@ -50,15 +54,20 @@ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
## Style Guide
### Code
Our linter will catch most styling issues that may exist in your code.
You can check the status of your code styling by simply running: `grunt lint`
* Use semicolons;
* Commas last,
However, there are still some styles that the linter cannot pick up. If you are unsure about something, looking at [Airbnb's Style Guide](https://github.com/airbnb/javascript) will guide you in the right direction.
### Code Conventions
* Use semicolons `;`
* Commas last `,`
* 2 spaces for indentation (no tabs)
* Prefer `'` over `"`
*`'use strict';`
* 80 character line length
*"Attractive"
*Write "attractive" code
* Do not use the optional parameters of `setTimeout` and `setInterval`
React is a JavaScript library for building user interfaces.
@@ -8,7 +8,7 @@ React is a JavaScript library for building user interfaces.
**NEW**! Check out our newest project [React Native](https://github.com/facebook/react-native), which uses React and JavaScript to create native mobile apps.
[Learn how to use React in your own project.](https://facebook.github.io/react/docs/getting-started.html).
[Learn how to use React in your own project](https://facebook.github.io/react/docs/getting-started.html).
## Examples
@@ -60,7 +60,7 @@ The process to build `react.js` is built entirely on top of node.js, using many
#### Prerequisites
* You have `node` installed at v0.10.0+ (it might work at lower versions, we just haven't tested).
* You have `node` installed at v0.10.0+ (it might work at lower versions, we just haven't tested) and `npm` at v2.0.0+.
* You are familiar with `npm` and know whether or not you need to use `sudo` when installing packages globally.
* You are familiar with `git`.
@@ -105,3 +105,6 @@ Examples provided in this repository and in the documentation are [separately li
### More…
There's only so much we can cram in here. To read more about the community and guidelines for submitting pull requests, please read the [Contributing document](CONTRIBUTING.md).
## Troubleshooting
See the [Troubleshooting Guide](https://github.com/facebook/react/wiki/Troubleshooting)
@@ -33,7 +33,7 @@ There are other features of ES6 we're already using in core. I'm sure we'll see
## Context
While we haven't documented `context`, it exists in some form in React already. It exists as a way to pass values through a tree without having to use props at every single point. We've seen this need crop up time and time again, so we want to make this as easy as possible. It's use has performance tradeoffs, and there are known weaknesses in our implementation, so we want to make sure this is a solid feature.
While we haven't documented `context`, it exists in some form in React already. It exists as a way to pass values through a tree without having to use props at every single point. We've seen this need crop up time and time again, so we want to make this as easy as possible. Its use has performance tradeoffs, and there are known weaknesses in our implementation, so we want to make sure this is a solid feature.
@@ -69,7 +69,7 @@ Obviously GraphQL is not the first system to manage client-server interactions.
### REST
REST, an acronym for Representational State Transfer, is an architectural style rather than a formal protocol. There is actually much debate about what exactly REST is and is not. We wish to avoid such debates. We are interested in the typical attributes of systems that *self-identify* as REST, rather than systems which are formally REST.
REST an acronym for Representational State Transfer, which is an architectural style rather than a formal protocol. There is actually much debate about what exactly REST is and is not. We wish to avoid such debates. We are interested in the typical attributes of systems that *self-identify* as REST, rather than systems which are formally REST.
Objects in a typical REST system are addressable by URI and interacted with using verbs in the HTTP protocol. An HTTP GET to a particular URI fetches an object and returns a server-specified set of fields. An HTTP PUT edits an object; an HTTP DELETE deletes an object; and so on.
Today we're excited to share an update on Relay - the technical preview is now open-source and [available on GitHub](http://github.com/facebook/relay).
## Why Relay
While React simplified the process of developing complex user-interfaces, it left open the question of how to interact with data on the server. It turns out that this was a significant source of friction for our developers; fragile coupling between client and server caused data-related bugs and made iteration harder. Furthermore, developers were forced to constantly re-implement complex async logic instead of focusing on their apps. Relay addresses these concerns by borrowing important lessons from React: it provides *declarative, component-oriented data fetching for React applications*.
Declarative data-fetching means that Relay applications specify *what* data they need, not *how* to fetch that data. Just as React uses a description of the desired UI to manage view updates, Relay uses a data description in the form of GraphQL queries. Given these descriptions, Relay coalesces queries into batches for efficiency, manages error-prone asynchronous logic, caches data for performance, and automatically updates views as data changes.
Relay is also component-oriented, extending the notion of a React component to include a description of what data is necessary to render it. This colocation allows developers to reason locally about their application and eliminates bugs such as under- or over-fetching data.
Relay is in use at Facebook in production apps, and we're using it more and more because *Relay lets developers focus on their products and move fast*. It's working for us and we'd like to share it with the community.
## What's Included
We're open-sourcing a technical preview of Relay - the core framework that we use internally, with some modifications for use outside Facebook. As this is the first release, it's good to keep in mind that there may be some incomplete or missing features. We'll continue to develop Relay and are working closely with the GraphQL community to ensure that Relay tracks updates during GraphQL's RFC period. But we couldn't wait any longer to get this in your hands, and we're looking forward to your feedback and contributions.
Relay is available on [GitHub](http://github.com/facebook/relay) and [npm](https://www.npmjs.com/package/react-relay).
## What's Next
The team is super excited to be releasing Relay - and just as excited about what's next. Here are some of the things we'll be focusing on:
- Offline support. This will allow applications to fulfill queries and enqueue updates without connectivity.
- Real-time updates. In collaboration with the GraphQL community, we're working to define a specification for subscriptions and provide support for them in Relay.
- A generic Relay. Just as the power of React was never about the virtual DOM, Relay is much more than a GraphQL client. We're working to extend Relay to provide a unified interface for interacting not only with server data, but also in-memory and native device data (and, even better, a mix of all three).
- Finally, it's all too easy as developers to focus on those people with the newest devices and fastest internet connections. We're working to make it easier to build applications that are robust in the face of slow or intermittent connectivity.
Last month, the first React.js European conference took place in the city of Paris, at ReactEurope. Attendees were treated to a range of talks covering React, React Native, Flux, Relay, and GraphQL. Big thanks to everyone involved with organizing the conference, to all the attendees, and everyone who gave their time to speak - it wouldn't have been possible without the help and support of the React community.
[Christopher Chedeau](https://github.com/vjeux) gave the opening keynote to the conference:
[Spencer Ahrens](https://github.com/sahrens) walks through building an advanced gestural UI leveraging the unique power of the React Native layout and animation systems to build a complex and fluid experience:
[Joseph Savona](https://github.com/josephsavona) explores the problems Relay solves, its architecture and the query lifecycle, and how can you use Relay to build more scalable apps. There are examples of how Relay powers applications as complex as the Facebook News Feed:
[Nick Schrock](https://github.com/schrockn) and [Dan Schafer](https://github.com/dschafer) take a deeper dive into putting GraphQL to work. How can we build a GraphQL API to work with an existing REST API or server-side data model? What are best practices when building a GraphQL API, and how do they differ from traditional REST best practices? How does Facebook use GraphQL? Most importantly, what does a complete and coherent GraphQL API looks like, and how can we get started building one?
[Sebastian Markbåge](https://github.com/sebmarkbage) talks about why the DOM is flawed and how it is becoming a second-class citizen in the land of React apps:
[Sebastian McKenzie](https://github.com/sebmck) goes over how existing JSX build pipeline infrastructure can be further utilised to perform even more significant code transformations such as transpilation, optimisation, profiling and more, reducing bugs, making your code faster and you as a developer more productive and happy:
[Cheng Lou](https://github.com/chenglou) gives a talk on the past, the present and the future of animation, and the place React can potentially take in this:
And there were lots of great talks from the React community:
* [Michael Chan](https://www.youtube.com/watch?v=ERB1TJBn32c&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD&index=2) looks at how to solve problems like CSS theming and media queries with contexts and plain old JavaScript. He also looks at the role of container-components and when it's better to "just use CSS.".
* [Elie Rotenberg](https://www.youtube.com/watch?v=JSjhhUvB9DY&index=3&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD) talks about Flux over the Wire, building isomorphic, real-time React apps using a novel interpretation of Flux.
* [Ryan Florence](https://www.youtube.com/watch?v=BF58ZJ1ZQxY&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD&index=6) says “Your front and back ends are already successfully in production but you don't have to miss out on the productivity that React brings. Forget the rewrites, this is brownfield!”.
* [Dan Abramov](https://www.youtube.com/watch?v=xsSnOQynTHs&index=7&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD) demonstrates how React can be used together with Webpack Hot Module Replacement to create a live editing environment with time travel that supercharges your debugging experience and transforms the way you work on real apps every day.
* [Mikhail Davydov](https://www.youtube.com/watch?v=ee_U2t-8L48&index=10&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD) shows you how to ask the browser layout engine for help, how to avoid slavery of DSL, and build declarative Text UI using only web-technologies like HTML, JS, CSS and React.
* [Kevin Robinson](https://www.youtube.com/watch?v=EOz4D_714R8&list=PLCC436JpVnK3HvUSAHpt-LRJkIK8pQG6R&index=3) shares how user experience choices are a primary influence on how Twitter design the data layer, especially for teams developing new products with full-stack capabilities.
* [Jed Watson](https://www.youtube.com/watch?v=ctwmd5L1U_Q&list=PLCC436JpVnK3HvUSAHpt-LRJkIK8pQG6R&index=4) shares what Thinkmill have learned about React and mobile app development, and how they've approached the unique challenges of mobile web apps - with tools that are useful to all developers building touch interfaces with React, as well as a walkthrough of their development process and framework.
* [Michael Jackson](https://www.youtube.com/watch?v=Q6Kczrgw6ic&list=PLCC436JpVnK3HvUSAHpt-LRJkIK8pQG6R&index=5) discusses how your users can benefit from the many tools that React Router provides including server-side rendering, real URLs on native devices, and much, much more.
* [Michael Ridgway](https://www.youtube.com/watch?v=MrozpFEBEBE&index=7&list=PLCC436JpVnK3HvUSAHpt-LRJkIK8pQG6R) walks you through an isomorphic Flux architecture to give you the holy grail of frontend development.
* [Aria Buckles](https://www.youtube.com/watch?v=2Qu-Ulrsfl8&index=8&list=PLCC436JpVnK3HvUSAHpt-LRJkIK8pQG6R) covers Khan Academy's techniques and patterns to make dealing with large pure components simpler, as well as current open questions.
* [Evan Morikawa and Ben Gotow](https://www.youtube.com/watch?v=Uu4Yz2HmCgE&index=9&list=PLCC436JpVnK3HvUSAHpt-LRJkIK8pQG6R) talk about specific features of React & Flux, React CSS, programming design patterns, and custom libraries, which can turn a static application into a dynamic platform that an ecosystem of developers can build on top of.
* [Zalando](https://www.youtube.com/watch?v=3EQhkquvVmY&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD&index=9), [Rangle.io](https://www.youtube.com/watch?v=nAWKR1bBDsU&index=12&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD), [Automattic](https://www.youtube.com/watch?v=hjhyrBbDp6U&index=13&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD), [Thinkmill](https://www.youtube.com/watch?v=ApoCktYaRxk&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD&index=14), and [Red Badger](https://www.youtube.com/watch?v=hdKidiwR8DM&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD&index=15) provided lots of insight into how larger companies are using React.
There was also a [great series of Lightning talks](https://www.youtube.com/playlist?list=PLCC436JpVnK3xnOZ727t0vd3nbb5ZqCyo) from [Joshua Sierles](https://github.com/jsierles), [Ovidiu Cherecheș](https://github.com/skidding), [Mike Grabowski](https://github.com/grabbou), [Dave Brotherstone](https://github.com/bruderstein), [Sunil Pai](https://github.com/threepointone), [Andreas Savvides](https://github.com/AnSavvides), and [Petr Bela](https://github.com/petrbela).
You can view the full list of talks on [the ReactEurope YouTube channel](https://www.youtube.com/channel/UCorlLn2oZfgOJ-FUcF2eZ1A).
A month ago, we [posted a beta](/react/blog/2015/08/03/new-react-devtools-beta.html) of the new React developer tools. Today, we're releasing the first stable version of the new devtools. We're calling it version 0.14, but it's a full rewrite so we think of it more like a 2.0 release.

It contains a handful of new features, including:
* Built entirely with React, making it easier to develop and extend
* Firefox support
* Selected component instance is available as `$r` from the console
* More detail is shown in props in the component tree
* Right-click any node and choose "Show Source" to jump to the `render` method in the Sources panel
* Right-click any props or state value to make it available as `$tmp` from the console
* Full React Native support
## Installation
Download the new devtools from the [Chrome Web Store](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi) and on [Mozilla Add-ons](https://addons.mozilla.org/en-US/firefox/addon/react-devtools/) for Firefox. If you're developing using React, we highly recommend installing these devtools.
If you already have the Chrome extension installed, it should autoupdate within the next week. You can also head to `chrome://extensions` and click "Update extensions now" if you'd like to get the new version today. If you installed the devtools beta, please remove it and switch back to the version from the store to make sure you always get the latest updates and bug fixes.
If you run into any issues, please post them on our [react-devtools GitHub repo](https://github.com/facebook/react-devtools).
We’re happy to announce our first release candidate for React 0.14! We gave you a [sneak peek in July](/react/blog/2015/07/03/react-v0.14-beta-1.html) at the upcoming changes but we’ve now stabilized the release more and we’d love for you to try it out before we release the final version.
Let us know if you run into any problems by filing issues on our [GitHub repo](https://github.com/facebook/react).
## Installation
We recommend using React from `npm` and using a tool like browserify or webpack to build your code into a single package:
*`npm install --save react@0.14.0-rc1`
*`npm install --save react-dom@0.14.0-rc1`
Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, set the `NODE_ENV` environment variable to `production` to use the production build of React which does not include the development warnings and runs significantly faster.
If you can’t use `npm` yet, we also provide pre-built browser builds for your convenience:
* **React**
Dev build with warnings: <https://fb.me/react-0.14.0-rc1.js>
Minified build for production: <https://fb.me/react-0.14.0-rc1.min.js>
***React with Add-Ons**
Dev build with warnings: <https://fb.me/react-with-addons-0.14.0-rc1.js>
Minified build for production: <https://fb.me/react-with-addons-0.14.0-rc1.min.js>
***React DOM** (include React in the page before React DOM)
Dev build with warnings: <https://fb.me/react-dom-0.14.0-rc1.js>
Minified build for production: <https://fb.me/react-dom-0.14.0-rc1.min.js>
These builds are also available in the `react` and `react-dom` packages on bower.
## Changelog
### Major changes
- #### Two Packages: React and React DOM
As we look at packages like [react-native](https://github.com/facebook/react-native), [react-art](https://github.com/reactjs/react-art), [react-canvas](https://github.com/Flipboard/react-canvas), and [react-three](https://github.com/Izzimach/react-three), it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.
To make this more clear and to make it easier to build more environments that React can render to, we’re splitting the main `react` package into two: `react` and `react-dom`. **This paves the way to writing components that can be shared between the web version of React and React Native.** We don’t expect all the code in an app to be shared, but we want to be able to share the components that do behave the same across platforms.
The `react` package contains `React.createElement`, `.createClass`, `.Component`, `.PropTypes`, `.Children`, and the other helpers related to elements and component classes. We think of these as the [_isomorphic_](http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/) or [_universal_](https://medium.com/@mjackson/universal-javascript-4761051b7ae9) helpers that you need to build components.
The `react-dom` package has `ReactDOM.render`, `.unmountComponentAtNode`, and `.findDOMNode`. In `react-dom/server` we have server-side rendering support with `ReactDOMServer.renderToString` and `.renderToStaticMarkup`.
```js
var React = require('react');
var ReactDOM = require('react-dom');
var MyComponent = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
ReactDOM.render(<MyComponent />, node);
```
We’ve published the [automated codemod script](https://github.com/facebook/react/blob/master/packages/react-codemod/README.md) we used at Facebook to help you with this transition.
The add-ons have moved to separate packages as well: `react-addons-clone-with-props`, `react-addons-create-fragment`, `react-addons-css-transition-group`, `react-addons-linked-state-mixin`, `react-addons-perf`, `react-addons-pure-render-mixin`, `react-addons-shallow-compare`, `react-addons-test-utils`, `react-addons-transition-group`, and `react-addons-update`, plus `ReactDOM.unstable_batchedUpdates` in `react-dom`.
For now, please use matching versions of `react` and `react-dom` in your apps to avoid versioning problems.
- #### DOM node refs
The other big change we’re making in this release is exposing refs to DOM components as the DOM node itself. That means: we looked at what you can do with a `ref` to a React DOM component and realized that the only useful thing you can do with it is call `this.refs.giraffe.getDOMNode()` to get the underlying DOM node. In this release, `this.refs.giraffe` _is_ the actual DOM node. **Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.**
// Previously: var input = this.refs.giraffe.getDOMNode();
var input = this.refs.giraffe;
alert(input.value);
}
});
```
This change also applies to the return result of `ReactDOM.render` when passing a DOM node as the top component. As with refs, this change does not affect custom components. With these changes, we’re deprecating `.getDOMNode()` and replacing it with `ReactDOM.findDOMNode` (see below).
- #### Stateless function components
In idiomatic React code, most of the components you write will be stateless, simply composing other components. We’re introducing a new, simpler syntax for these components where you can take `props` as an argument and return the element you want to render:
```js
// Using an ES2015 (ES6) arrow function:
var Aquarium = (props) => {
var fish = getFish(props.species);
return <Tank>{fish}</Tank>;
};
// Or with destructuring and an implicit return, simply:
var Aquarium = ({species}) => (
<Tank>
{getFish(species)}
</Tank>
);
// Then use: <Aquarium species="rainbowfish" />
```
This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.
- #### Deprecation of react-tools
The `react-tools` package and `JSXTransformer.js` browser file [have been deprecated](/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html). You can continue using version `0.13.3` of both, but we no longer support them and recommend migrating to [Babel](http://babeljs.io/), which has built-in support for React and JSX.
- #### Compiler optimizations
React now supports two compiler optimizations that can be enabled in Babel 5.8.23 and newer. Both of these transforms **should be enabled only in production** (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.
**Inlining React elements:** The `optimisation.react.inlineElements` transform converts JSX elements to object literals like `{type: 'div', props: ...}` instead of calls to `React.createElement`.
**Constant hoisting for React elements:** The `optimisation.react.constantElements` transform hoists element creation to the top level for subtrees that are fully static, which reduces calls to `React.createElement` and the resulting allocations. More importantly, it tells React that the subtree hasn’t changed so React can completely skip it when reconciling.
### Breaking changes
As always, we have a few breaking changes in this release. Whenever we make large changes, we warn for at least one release so you have time to update your code. The Facebook codebase has over 15,000 React components, so on the React team, we always try to minimize the pain of breaking changes.
These three breaking changes had a warning in 0.13, so you shouldn’t have to do anything if your code is already free of warnings:
- The `props` object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, [`React.cloneElement`](/react/docs/top-level-api.html#react.cloneelement) should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.
- Plain objects are no longer supported as React children; arrays should be used instead. You can use the [`createFragment`](/react/docs/create-fragment.html) helper to migrate, which now returns an array.
- Add-Ons: `classSet` has been removed. Use [classnames](https://github.com/JedWatson/classnames) instead.
And these two changes did not warn in 0.13 but should be easy to find and clean up:
- `React.initializeTouchEvents` is no longer necessary and has been removed completely. Touch events now work automatically.
- Add-Ons: Due to the DOM node refs change mentioned above, `TestUtils.findAllInRenderedTree` and related helpers are no longer able to take a DOM component, only a custom component.
### New deprecations, introduced with a warning
- Due to the DOM node refs change mentioned above, `this.getDOMNode()` is now deprecated and `ReactDOM.findDOMNode(this)` can be used instead. Note that in most cases, calling `findDOMNode` is now unnecessary – see the example above in the “DOM node refs” section.
If you have a large codebase, you can use our [automated codemod script](https://github.com/facebook/react/blob/master/packages/react-codemod/README.md) to change your code automatically.
- `setProps` and `replaceProps` are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.
- ES6 component classes must now extend `React.Component` in order to enable stateless function components. The [ES3 module pattern](/react/blog/2015/01/27/react-v0.13.0-beta-1.html#other-languages) will continue to work.
- Reusing and mutating a `style` object between renders has been deprecated. This mirrors our change to freeze the `props` object.
- Add-Ons: `cloneWithProps` is now deprecated. Use [`React.cloneElement`](/react/docs/top-level-api.html#react.cloneelement) instead (unlike `cloneWithProps`, `cloneElement` does not merge `className` or `style` automatically; you can merge them manually if needed).
- Add-Ons: To improve reliability, `CSSTransitionGroup` will no longer listen to transition events. Instead, you should specify transition durations manually using props such as `transitionEnterTimeout={500}`.
### Notable enhancements
- Added `React.Children.toArray` which takes a nested children object and returns a flat array with keys assigned to each child. This helper makes it easier to manipulate collections of children in your `render` methods, especially if you want to reorder or slice `this.props.children` before passing it down. In addition, `React.Children.map` now returns plain arrays too.
- React uses `console.error` instead of `console.warn` for warnings so that browsers show a full stack trace in the console. (Our warnings appear when you use patterns that will break in future releases and for code that is likely to behave unexpectedly, so we do consider our warnings to be “must-fix” errors.)
- Previously, including untrusted objects as React children [could result in an XSS security vulnerability](http://danlec.com/blog/xss-via-a-spoofed-react-element). This problem should be avoided by properly validating input at the application layer and by never passing untrusted objects around your application code. As an additional layer of protection, [React now tags elements](https://github.com/facebook/react/pull/4832) with a specific [ES2015 (ES6) `Symbol`] (http://www.2ality.com/2014/12/es6-symbols.html) in browsers that support it, in order to ensure that React never considers untrusted JSON to be a valid element. If this extra security protection is important to you, you should add a `Symbol` polyfill for older browsers, such as the one included by [Babel’s polyfill](http://babeljs.io/docs/usage/polyfill/).
- When possible, React DOM now generates XHTML-compatible markup.
- React DOM now supports these standard HTML attributes: `capture`, `challenge`, `inputMode`, `is`, `keyParams`, `keyType`, `minLength`, `summary`, `wrap`. It also now supports these non-standard attributes: `autoSave`, `results`, `security`.
- React DOM now supports these SVG attributes, which render into namespaced attributes: `xlinkActuate`, `xlinkArcrole`, `xlinkHref`, `xlinkRole`, `xlinkShow`, `xlinkTitle`, `xlinkType`, `xmlBase`, `xmlLang`, `xmlSpace`.
- The `image` SVG tag is now supported by React DOM.
- In React DOM, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an `is="..."` attribute).
- React DOM now supports these media events on `audio` and `video` tags: `onAbort`, `onCanPlay`, `onCanPlayThrough`, `onDurationChange`, `onEmptied`, `onEncrypted`, `onEnded`, `onError`, `onLoadedData`, `onLoadedMetadata`, `onLoadStart`, `onPause`, `onPlay`, `onPlaying`, `onProgress`, `onRateChange`, `onSeeked`, `onSeeking`, `onStalled`, `onSuspend`, `onTimeUpdate`, `onVolumeChange`, `onWaiting`.
- Many small performance improvements have been made.
- Many warnings show more context than before.
- Add-Ons: A [`shallowCompare`](https://github.com/facebook/react/pull/3355) add-on has been added as a migration path for `PureRenderMixin` in ES6 classes.
- Add-Ons: `CSSTransitionGroup` can now use [custom class names](https://github.com/facebook/react/blob/48942b85/docs/docs/10.1-animation.md#custom-classes) instead of appending `-enter-active` or similar to the transition name.
### New helpful warnings
- React DOM now warns you when nesting HTML elements invalidly, which helps you avoid surprising errors during updates.
- Passing `document.body` directly as the container to `ReactDOM.render` now gives a warning as doing so can cause problems with browser extensions that modify the DOM.
- Using multiple instances of React together is not supported, so we now warn when we detect this case to help you avoid running into the resulting problems.
### Notable bug fixes
- Click events are handled by React DOM more reliably in mobile browsers, particularly in Mobile Safari.
- SVG elements are created with the correct namespace in more cases.
- React DOM now renders `<option>` elements with multiple text children properly and renders `<select>` elements on the server with the correct option selected.
- When two separate copies of React add nodes to the same document (including when a browser extension uses React), React DOM tries harder not to throw exceptions during event handling.
- Using non-lowercase HTML tag names in React DOM (e.g., `React.createElement('DIV')`) no longer causes problems, though we continue to recommend lowercase for consistency with the JSX tag name convention (lowercase names refer to built-in components, capitalized names refer to custom components).
- React DOM understands that these CSS properties are unitless and does not append “px” to their values: `animationIterationCount`, `boxOrdinalGroup`, `flexOrder`, `tabSize`, `stopOpacity`.
- Add-Ons: When using the test utils, `Simulate.mouseEnter` and `Simulate.mouseLeave` now work.
- Add-Ons: ReactTransitionGroup now correctly handles multiple nodes being removed simultaneously.
In the weeks following the [open-source release](/react/blog/2015/08/11/relay-technical-preview.html) of the Relay technical preview, the community has been abuzz with activity. We are honored to have been able to enjoy a steady stream of ideas and contributions from such a talented group of individuals. Let's take a look at some of the things we've achieved, together!
## Teaching servers to speak GraphQL
Every great Relay app starts by finding a GraphQL server to talk to. The community has spent the past few weeks teaching GraphQL to a few backend systems.
Bryan Goldstein ([brysgo](https://github.com/brysgo)) has built a tool to help you define a GraphQL schema that wraps a set of [Bookshelf.JS](http://bookshelfjs.org/) models. Check out [graphql-bookshelf](https://github.com/brysgo/graphql-bookshelf).
RisingStack ([risingstack](https://github.com/risingstack)) created a GraphQL ORM called [graffiti](https://github.com/RisingStack/graffiti) that you can plug into [mongoose](http://mongoosejs.com/) and serve using Express, Hapi, or Koa.
David Mongeau-Petitpas ([dmongeau](https://github.com/dmongeau)) is working on a way to vend your Laravel models through a GraphQL endpoint, [laravel-graphql](https://github.com/Folkloreatelier/laravel-graphql).
Gerald Monaco ([devknoll](https://github.com/devknoll)) created [graphql-schema](https://github.com/devknoll/graphql-schema) to allow the creation of JavaScript GraphQL schemas using a fluent/chainable interface.
Jason Dusek ([solidsnack](https://github.com/solidsnack)) dove deep into PostgreSQL to teach it how to respond to GraphQL query strings as though they were SQL queries. Check out [GraphpostgresQL](https://github.com/solidsnack/GraphpostgresQL).
Espen Hovlandsdal ([rexxars](https://github.com/rexxars)) built a [sql-to-graphql](https://github.com/vaffel/sql-to-graphql) tool that can perform introspection on the tables of a MySQL or PostgreSQL database, and produce a queryable HTTP GraphQL endpoint out of it.
Mick Hansen ([mickhansen](https://github.com/mickhansen)) offers a set of [schema-building helpers](https://github.com/mickhansen/graphql-sequelize) for use with the [Sequelize ORM](http://docs.sequelizejs.com/en/latest/) for MySQL, PostgreSQL, SQLite, and MSSQL.
## GraphQL beyond JavaScript
Robert Mosolgo ([rmosolgo](https://github.com/rmosolgo)) brought the full set of schema-building and query execution tools to Ruby, in the form of [graphql-ruby](https://github.com/rmosolgo/graphql-ruby) and [graphql-relay-ruby](https://github.com/rmosolgo/graphql-relay-ruby). Check out his [Rails-based demo](https://github.com/rmosolgo/graphql-ruby-demo).
Andreas Marek ([andimarek](https://github.com/andimarek)) has brewed up a Java implementation of GraphQL, [graphql-java](https://github.com/andimarek/graphql-java).
[vladar](https://github.com/vladar) is hard at work on a PHP port of the GraphQL reference implementation, [graphql-php](https://github.com/webonyx/graphql-php).
Taeho Kim ([dittos](https://github.com/dittos)) is bringing GraphQL to Python, with [graphql-py](https://github.com/dittos/graphql-py).
Oleg Ilyenko ([OlegIlyenko](https://github.com/OlegIlyenko)) made a beautiful and [delicious-looking website](http://sangria-graphql.org/) for a Scala implementation of GraphQL, [sangria](https://github.com/sangria-graphql/sangria).
Joe McBride ([joemcbride](https://github.com/joemcbride)) has an up-and-running example of GraphQL for .NET, [graphql-dotnet](https://github.com/joemcbride/graphql-dotnet).
## Show me, don't tell me
Interact with this [visual tour of Relay's architecture](http://sgwilym.github.io/relay-visual-learners/) by Sam Gwilym ([sgwilym](https://github.com/sgwilym)).
<img src="/react/img/blog/relay-visual-architecture-tour.png" alt="Relay for visual learners" style="max-width:100%">
</a>
Sam has already launched a product that leverages Relay's data-fetching, optimistic responses, pagination, and mutations – all atop a Ruby GraphQL server: [new.comique.co](http://new.comique.co/)
## Prototyping in the browser
I ([steveluscher](https://github.com/steveluscher)) whipped up [a prototyping tool](https://facebook.github.io/relay/prototyping/playground.html) that you can use to hack on a schema and a React/Relay app, from the comfort of your browser. Thanks to Jimmy Jia ([taion](https://github.com/taion)) for supplying the local-only network layer, [relay-local-schema](https://github.com/relay-tools/relay-local-schema).
## Skeletons in the closet
Joseph Rollins ([fortruce](https://github.com/fortruce)) created a hot-reloading, auto schema-regenerating, [Relay skeleton](https://github.com/fortruce/relay-skeleton) that you can use to get up and running quickly.
Michael Hart ([mhart](https://mhart)) built a [simple-relay-starter](https://github.com/mhart/simple-relay-starter) kit using Browserify.
## Routing around
Jimmy Jia ([taion](https://github.com/taion)) and Gerald Monaco ([devknoll](https://github.com/devknoll)) have been helping lost URLs find their way to Relay apps through their work on [react-router-relay](https://github.com/relay-tools/react-router-relay). Check out Christoph Pojer's ([cpojer](https://github.com/cpojer)) [blog post](https://medium.com/@cpojer/relay-and-routing-36b5439bad9) on the topic. Jimmy completed the Relay TodoMVC example with routing, which you can check out at [taion/relay-todomvc](https://github.com/taion/relay-todomvc).
Chen Hung-Tu ([transedward](https://github.com/transedward)) built a chat app atop the above mentioned router, with threaded conversations and pagination. Check it out at [transedward/relay-chat](https://github.com/transedward/relay-chat).
## In your words
<div class="skinny-row">
<div class="skinny-col">
<blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">Relay making good on its promise to be the "React.js of data fetching". Rebuilding small app with it. Spectacular how fast/easy building is.</p>— Kyle Mathews (@kylemathews) <a href="https://twitter.com/kylemathews/status/640289107122368513">September 5, 2015</a></blockquote>
<blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">Friday. Time to GraphQL a MySQL database. <a href="https://twitter.com/hashtag/graphql?src=hash">#graphql</a> <a href="https://twitter.com/hashtag/relayjs?src=hash">#relayjs</a> <a href="https://twitter.com/hashtag/reactjs?src=hash">#reactjs</a> <a href="https://twitter.com/hashtag/webapp?src=hash">#webapp</a></p>— xador (@xadorfr) <a href="https://twitter.com/xadorfr/status/632108552765751296">August 14, 2015</a></blockquote>
</div>
<div class="skinny-col">
<blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">Started a new <a href="https://twitter.com/hashtag/RelayJS?src=hash">#RelayJS</a> and <a href="https://twitter.com/hashtag/GraphQL?src=hash">#GraphQL</a> meet up group! <a href="http://t.co/Vt6Cv4nNH4">http://t.co/Vt6Cv4nNH4</a> If you're in the Bay Area, I'd love to have you join! <a href="https://twitter.com/hashtag/ReactJS?src=hash">#ReactJS</a></p>— Gerald Monaco (@devknoll) <a href="https://twitter.com/devknoll/status/636723716123000832">August 27, 2015</a></blockquote>
<blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">.<a href="https://twitter.com/reactjs">@reactjs</a> <a href="https://twitter.com/laneykuenzel">@laneykuenzel</a> <a href="https://twitter.com/BhuwanKhattar">@BhuwanKhattar</a> these <a href="https://twitter.com/hashtag/relayjs?src=hash">#relayjs</a> mutations. they're mind-blowingly awesome. they make so much damn sense. thank you!</p>— Jimmy Jia (@jimmy_jia) <a href="https://twitter.com/jimmy_jia/status/634204563709526016">August 20, 2015</a></blockquote>
<blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">REST is dead, long live REST! <a href="https://twitter.com/hashtag/graphql?src=hash">#graphql</a> <a href="https://twitter.com/hashtag/relayjs?src=hash">#relayjs</a></p>— Syrus Akbary (@syrusakbary) <a href="https://twitter.com/syrusakbary/status/631531666113060864">August 12, 2015</a></blockquote>
When you're in React's world you are just building components that fit into other components. Everything is a component. Unfortunately not everything around you is built using React. At the root of your tree you still have to write some plumbing code to connect the outer world into React.
The primary API for rendering into the DOM looks like this:
```js
ReactDOM.render(reactElement,domContainerNode)
```
To update the properties of an existing component, you call render again with a new element.
If you are rendering React components within a single-page app, you may need to plug into the app's view lifecycle to ensure your app will invoke unmountComponentAtNode at the appropriate time. React will not automatically clean up a tree. You need to manually call:
```js
ReactDOM.unmountComponentAtNode(domContainerNode)
```
This is important and often forgotten. Forgetting to call `unmountComponentAtNode` will cause your app to leak memory. There is no way for us to automatically detect when it is appropriate to do this work. Every system is different.
It is not unique to the DOM. If you want to insert a React Native view in the middle of an existing iOS app you will hit similar issues.
## Helpers
If you have multiple React roots, or a single root that gets deleted over time, we recommend that you always create your own wrapper API. These will all look slightly different depending on what your outer system looks like. For example, at Facebook we have a system that automatically ties into our page transition router to automatically call `unmountComponentAtNode`.
Rather than calling `ReactDOM.render()` directly everywhere, consider writing/using a library that will manage mounting and unmounting within your application.
In your environment you may want to always configure internationalization, routers, user data etc. If you have many different React roots it can be a pain to set up configuration nodes all over the place. By creating your own wrapper you can unify that configuration into one place.
## Object Oriented Updates
If you call `ReactDOM.render` a second time to update properties, all your props are completely replaced.
In object-oriented programming, all state lives on each object instance and you apply changes incrementally by mutating that state, one piece at a time. If you are using React within an app that expects an object oriented API (for instance, if you are building a custom web component using React), it might be surprising/confusing to a user that setting a single property would wipe out all the other properties on your component.
We used to have a helper function called `setProps` which allowed you to update only a few properties at a time. Unfortunately this API lived on a component instance, required React to keep this state internally and wasn't very natural anyway. Therefore, we're deprecating it and suggest that you build it into your own wrapper instead.
Here's some boilerplate to get you started. It is a 0.14 migration path for codebases using `setProps` and `replaceProps`.
```js
classReactComponentRenderer{
constructor(klass,container){
this.klass=klass;
this.container=container;
this.props={};
this.component=null;
}
replaceProps(props,callback){
this.props={};
this.setProps(props,callback);
}
setProps(partialProps,callback){
if(this.klass==null){
console.warn(
'setProps(...): Can only update a mounted or '+
'mounting component. This usually means you called setProps() on '+
Object-oriented APIs don't look like that though. They use setters and methods. I think we can do better. If you know more about the component API that you're rendering, you can create a more natural object-oriented API around your React component.
This example shows how to provide an imperative API on top of a declarative one. Similarly, the reverse can be done, and a declarative wrapper can be used when exposing a Web Component as a React component.
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](https://www.npmjs.com/package/react-tools) package.
We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.**
JSX is very small. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [the Babel REPL](https://babeljs.io/repl/).
JSX is very small. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
[Babel exposes a number of ways to get started using JSX](http://babeljs.io/docs/setup/), ranging from command line tools to Ruby on Rails integrations. Choose the tool that works best for you.
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](https://www.npmjs.com/package/react-tools) package.
@@ -27,7 +27,7 @@ If you want to display an HTML entity within dynamic content, you will run into
<div>{'First · Second'}</div>
```
There are various ways to work-around this issue. The easiest one is to write unicode characters directly in JavaScript. You need to make sure that the file is saved as UTF-8 and that the proper UTF-8 directives are set so the browser will display it correctly.
There are various ways to work-around this issue. The easiest one is to write unicode character directly in JavaScript. You need to make sure that the file is saved as UTF-8 and that the proper UTF-8 directives are set so the browser will display it correctly.
With React you simply pass your event handler as a camelCased prop similar to how you'd do it in normal HTML. React ensures that all events behave identically in IE8 and above by implementing a synthetic event system. That is, React knows how to bubble and capture events according to the spec, and the events passed to your event handler are guaranteed to be consistent with [the W3C spec](http://www.w3.org/TR/DOM-Level-3-Events/), regardless of which browser you're using.
If you'd like to use React on a touch device such as a phone or tablet, simply call `React.initializeTouchEvents(true);` to enable touch event handling.
## Under the Hood: Autobinding and Event Delegation
Under the hood, React does a few things to keep your code performant and easy to understand.
**Autobinding:** When creating callbacks in JavaScript, you usually need to explicitly bind a method to its instance such that the value of `this` is correct. With React, every method is automatically bound to its component instance (except when using ES6 class syntax). React caches the bound method such that it's extremely CPU and memory efficient. It's also less typing!
**Autobinding:** When creating callbacks in JavaScript, you usually need to explicitly bind a method to its instance such that the value of `this` is correct. With React, every method is automatically bound to its component instance. React caches the bound method such that it's extremely CPU and memory efficient. It's also less typing!
**Event delegation:** React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops. To learn more about why this is fast, see [David Walsh's excellent blog post](http://davidwalsh.name/event-delegate).
In the above example, instances of `Avatar`*own* instances of `ProfilePic` and `ProfileLink`. In React, **an owner is the component that sets the `props` of other components**. More formally, if a component `X` is created in component `Y`'s `render()` method, it is said that `X` is *owned by*`Y`. As discussed earlier, a component cannot mutate its `props` — they are always consistent with what its owner sets them to. This fundamental invariant leads to UIs that are guaranteed to be consistent.
In the above example, instances of `Avatar`*own* instances of `ProfilePic` and `ProfileLink`. In React, **an owner is the component that sets the `props` of other components**. More formally, if a component `X` is created in component `Y`'s `render()` method, it is said that `X` is *owned by*`Y`. As discussed earlier, a component cannot mutate its `props` — they are always consistent with what its owner sets them to. This key property leads to UIs that are guaranteed to be consistent.
It's important to draw a distinction between the owner-ownee relationship and the parent-child relationship. The owner-ownee relationship is specific to React, while the parent-child relationship is simply the one you know and love from the DOM. In the example above, `Avatar` owns the `div`, `ProfilePic` and `ProfileLink` instances, and `div` is the **parent** (but not owner) of the `ProfilePic` and `ProfileLink` instances.
@@ -181,7 +181,7 @@ In React, data flows from owner to owned component through `props` as discussed
## A Note on Performance
You may be thinking that it's expensive to change 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. React will optimize this for you by using batching and change detection.
You may be thinking that it's expensive to change 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. React will optimize this for you using batching and change detection.
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](/react/docs/component-specs.html) for more information.
@@ -24,7 +24,7 @@ The rest of this tutorial explains best practices. It uses JSX and experimental
## Manual Transfer
Most of the time you should explicitly pass the properties down. This ensures that you only expose a subset of the inner API, one that you know will work.
Most of the time you should explicitly pass the properties down. That ensures that you only expose a subset of the inner API, one that you know will work.
```javascript
varFancyCheckbox=React.createClass({
@@ -51,7 +51,7 @@ But what about the `name` prop? Or the `title` prop? Or `onMouseOver`?
> NOTE:
>
> The `...` syntax is part of the Object Rest Spread proposal. This proposal is on track to become a standard. See the [Rest and Spread Properties ...](/react/docs/transferring-props.html#rest-and-spread-properties-...) section below for more details.
> In the example below, the `--harmony ` flag is required as this syntax is an experimental ES7 syntax. If using the in-browser JSX transformer, simply open your script with `<script type="text/jsx;harmony=true">`. See the [Rest and Spread Properties ...](/react/docs/transferring-props.html#rest-and-spread-properties-...) section below for more details.
Sometimes it's fragile and tedious to pass every property along. In that case you can use [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) with rest properties to extract a set of unknown properties.
@@ -143,7 +143,7 @@ z; // { a: 3, b: 4 }
> Note:
>
> This proposal has reached stage 2 and is now enabled by default in Babel. Older versions of Babel may need to explicitly enable this transform with `babel --optional es7.objectRestSpread`
> Use the [JSX command-line tool](https://www.npmjs.com/package/react-tools) with the `--harmony` flag to activate the experimental ES7 syntax.
After returning the structure of your UI from the render method, you may find yourself wanting to "reach out" and invoke methods on component instances returned from `render()`. Often, doing something like this isn't necessary for making data flow through your application, because the Reactive data flow always ensures that the most recent `props` are sent to each child that is output from `render()`. However, there are a few cases where it still might be necessary or beneficial.
After returning the structure of your UI from the render method, you may find yourself wanting to "reach out" and invoke methods on component instances returned from render. Often, doing something like this isn't necessary for making data flow through your application, because the Reactive data flow always ensures that the most recent `props` are sent to each child that is output from `render()`. However, there are a few cases where it still might be necessary or beneficial.
Consider the case, when you wish to tell an `<input />` element (that exists within your instances sub-hierarchy) to focus after you update its value to be the empty string, `''`.
@@ -73,15 +73,15 @@ It's as simple as:
1. Assign a `ref` attribute to anything returned from `render` such as:
```html
<input ref="myInput" />
```
```html
<input ref="myInput" />
```
2. In some other code (typically event handler code), access the **backing instance** via `this.refs` as in:
```javascript
this.refs.myInput
```
```javascript
this.refs.myInput
```
You can access the component's DOM node directly by calling `React.findDOMNode(this.refs.myInput)`.
@@ -90,33 +90,11 @@ It's as simple as:
The `ref` attribute can be a callback function instead of a name. This callback will be executed immediately after the component is mounted. The referenced component will be passed in as a parameter, and the callback function may use the component immediately, or save the reference for future use (or both).
It's as simple as adding a `ref` attribute to anything returned from `render` by using an ES6 arrow function:
It's as simple as assigning a `ref` attribute to anything returned from `render` such as:
Note that when the referenced component is unmounted and whenever the ref changes, the old ref will be called with `null` as an argument. This prevents memory leaks in the case that the instance is stored, as in the first example. Note that when writing refs with inline function expressions as in the examples here, React sees a different function object each time so on every update, ref will be called with `null` immediately before it's called with the component instance.
@@ -23,7 +23,7 @@ We have instructions for building from `master` [in our GitHub repository](https
### In-browser JSX Transform
If you like using JSX, Babel provides an [in-browser ES6 and JSX transformer for development](http://babeljs.io/docs/usage/browser/) called browser.js that can be included from a `babel-core` npm release or from [CDNJS](http://cdnjs.com/libraries/babel-core). Include a `<script type="text/babel">` tag to engage the JSX transformer.
If you like using JSX, we provide an in-browser JSX transformer for development [on our download page](/react/downloads.html). Simply include a `<script type="text/jsx">` tag to engage the JSX transformer.
> Note:
>
@@ -32,41 +32,11 @@ If you like using JSX, Babel provides an [in-browser ES6 and JSX transformer for
### Productionizing: Precompiled JSX
If you have [npm](https://www.npmjs.com/), you can run `npm install -g babel`. Babel has built-in support for React v0.12 and v0.13. Tags are automatically transformed to their equivalent `React.createElement(...)`, `displayName` is automatically inferred and added to all React.createClass calls.
If you have [npm](https://www.npmjs.com/), you can simply run `npm install -g react-tools` to install our command-line `jsx` tool. This tool will translate files that use JSX syntax to plain JavaScript files that can run directly in the browser. It will also watch directories for you and automatically transform files when they are changed; for example: `jsx --watch src/ build/`.
This tool will translate files that use JSX syntax to plain JavaScript files that can run directly in the browser. It will also watch directories for you and automatically transform files when they are changed; for example: `babel --watch src/ --out-dir lib/`.
By default JSX files with a `.js` extension are transformed. Use `jsx --extension jsx src/ build/` to transform files with a `.jsx` extension.
By default JSX files with a`.js` extension are transformed. Run `babel --help` for more information on how to use Babel.
@@ -54,7 +54,7 @@ var TodoList = React.createClass({
```
> Note:
>
> You must provide [the `key` attribute](/react/docs/multiple-components.html#dynamic-children) for all children of `ReactCSSTransitionGroup`, even when only rendering a single item. This is how React will determine which children have entered, left, or stayed.
> You must provide [the `key` attribute](/react/docs/multiple-components.html#dynamic-children) for all children of `ReactCSSTransitionGroup`, even if rendering a single item. This is how React will determine which children have entered, left, or stayed.
In this component, when a new item is added to `ReactCSSTransitionGroup` it will get the `example-enter` CSS class and the `example-enter-active` CSS class added in the next tick. This is a convention based on the `transitionName` prop.
@@ -117,6 +117,35 @@ At the initial mount, all children of the `ReactCSSTransitionGroup` will `appear
>
> The prop `transitionAppear` was added to `ReactCSSTransitionGroup` in version `0.13`. To maintain backwards compatibility, the default value is set to `false`.
### Custom Classes
It is also possible to use custom class names for each of the steps in your transitions. Instead of passing a string into transitionName you can pass an object containing either the `enter` and `leave` class names, or an object containing the `enter`, `enter-active`, `leave-active`, and `leave` class names. If only the enter and leave classes are provided, the enter-active and leave-active classes will be determined by appending '-active' to the end of the class name. Here are two examples using custom classes:
```javascript
...
<ReactCSSTransitionGroup
transitionName={
enter: 'enter',
enterActive: 'enterActive',
leave: 'leave',
leaveActive: 'leaveActive',
appear: 'appear',
appearActive: 'appearActive'
}>
{item}
</ReactCSSTransitionGroup>
<ReactCSSTransitionGroup
transitionName={
enter: 'enter',
leave: 'leave',
appear: 'appear'
}>
{item2}
</ReactCSSTransitionGroup>
...
```
### Animation Group Must Be Mounted To Work
In order for it to apply transitions to its children, the `ReactCSSTransitionGroup` must already be mounted in the DOM or the prop `transitionAppear` must be set to `true`. The example below would not work, because the `ReactCSSTransitionGroup` is being mounted along with the new item, instead of the new item being mounted within it. Compare this to the [Getting Started](#getting-started) section above to see the difference.
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.
`classSet()` also lets you pass class names in as arguments that are then concatenated for you:
`classSet()` also lets pass class names in as arguments that are then concatenated for you:
Simulate an event dispatch on a DOM node with optional `eventData` event data. **This is possibly the single most useful utility in `ReactTestUtils`.**
**Clicking an element**
```javascript
varnode=React.findDOMNode(this.refs.button);
React.addons.TestUtils.Simulate.click(node);
```
**Changing the value of an input field and then pressing ENTER**
*note that you will have to provide any event property that you're using in your component (e.g. keyCode, which, etc...) as React is not creating any of these for you*
`Simulate` has a method for every event that React understands.
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.
@@ -63,9 +46,7 @@ Pass a mocked component module to this method to augment it with useful methods
### isElement
```javascript
booleanisElement(
ReactElementelement
)
booleanisElement(ReactElementelement)
```
Returns `true` if `element` is any ReactElement.
@@ -73,10 +54,7 @@ Returns `true` if `element` is any ReactElement.
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.
@@ -126,9 +94,7 @@ Traverse all components in `tree` and accumulate all components where `test(comp
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.
@@ -147,10 +110,7 @@ Like `scryRenderedDOMComponentsWithClass()` but expects there to be one result,
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.
@@ -169,10 +126,7 @@ Like `scryRenderedDOMComponentsWithTag()` but expects there to be one result, an
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.
Call this in your tests to create a shallow renderer. You can think of this as a "place" to render the component you're testing, where it can respond to events and update itself.
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.
While this is fairly performant (since it only makes a shallow copy of`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:
@@ -21,8 +21,6 @@ The `Perf` object documented here is exposed as `React.addons.Perf` when using t
### `Perf.start()` and `Perf.stop()`
Start/stop the measurement. The React operations in-between are recorded for analyses below. Operations that took an insignificant amount of time are ignored.
After stopping, you will need `Perf.getLastMeasurements()` (described below) to get the measurements.
### `Perf.printInclusive(measurements)`
Prints the overall time taken. If no argument's passed, defaults to all the measurements from the last recording. This prints a nicely formatted table in the console, like so:
@@ -45,7 +45,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
</html>
```
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](/react/docs/jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/babel">` and include Babel 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.
Note that some browsers (Chrome, e.g.) will fail to load the file unless it's served via HTTP.
### Offline Transform
First install the [Babel](http://babeljs.io/) command-line tools (requires [npm](https://www.npmjs.com/)):
First install the command-line tools (requires [npm](https://www.npmjs.com/)):
```
npm install --global babel
npm install -g react-tools
```
Then, translate your `src/helloworld.js` file to plain JavaScript:
```
babel src --watch --out-dir build
jsx --watch src/ build/
```
The file `build/helloworld.js` is autogenerated whenever you make a change. Read the [Babel CLI documentation](http://babeljs.io/docs/usage/cli/) for more advanced usage.
The file `build/helloworld.js` is autogenerated whenever you make a change.
```javascript{2}
React.render(
@@ -100,7 +100,7 @@ Update your HTML file as below:
@@ -154,15 +154,6 @@ If this component has been mounted into the DOM, this returns the corresponding
`React.PropTypes` includes types that can be used with a component's `propTypes` object to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html).
### React.initializeTouchEvents
```javascript
initializeTouchEvents(booleanshouldUseTouch)
```
Configure React's event system to handle touch events on mobile devices.
### React.Children
`React.Children` provides utilities for dealing with the `this.props.children` opaque data structure.
Performs a shallow merge of nextState into current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks.
Merges nextState with the current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks.
The first argument can be an object (containing zero or more keys to update) or a function (of state and props) that returns an object containing keys to update.
Here is the simple object usage:
Here is the simple object usage...
```javascript
setState({mykey:'my new value'});
@@ -53,10 +50,7 @@ The second (optional) parameter is a callback function that will be executed onc
### replaceState
```javascript
replaceState(
objectnextState,
[functioncallback]
)
replaceState(objectnextState[,functioncallback])
```
Like `setState()` but deletes any pre-existing state keys that are not in nextState.
@@ -69,9 +63,7 @@ Like `setState()` but deletes any pre-existing state keys that are not in nextSt
### forceUpdate
```javascript
forceUpdate(
[functioncallback]
)
forceUpdate([functioncallback])
```
By default, when your component's state or props change, your component will re-render. However, if these change implicitly (eg: data deep within an object changes without changing the object itself) or if your `render()` method depends on some other data, you can tell React that it needs to re-run `render()` by calling `forceUpdate()`.
@@ -102,7 +94,7 @@ If this component has been mounted into the DOM, this returns the corresponding
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()`.
`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()`.
> Note:
>
@@ -112,10 +104,7 @@ bool isMounted()
### setProps
```javascript
setProps(
objectnextProps,
[functioncallback]
)
setProps(objectnextProps[,functioncallback])
```
When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with `React.render()`.
@@ -133,10 +122,7 @@ Calling `setProps()` on a root-level component will change its properties and tr
### replaceProps
```javascript
replaceProps(
objectnextProps,
[functioncallback]
)
replaceProps(objectnextProps[,functioncallback])
```
Like `setProps()` but deletes any pre-existing props instead of merging the two objects.
@@ -121,7 +121,7 @@ Invoked once, both on the client and server, immediately before the initial rend
componentDidMount()
```
Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. At this point in the lifecycle, the component has a DOM representation which you can access via `React.findDOMNode(this)`. The `componentDidMount()` method of child components is invoked before that of parent components.
Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. At this point in the lifecycle, the component has a DOM representation which you can access via `React.findDOMNode(this)`.
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.
@@ -129,9 +129,7 @@ If you want to integrate with other JavaScript frameworks, set timers using `set
### Updating: componentWillReceiveProps
```javascript
componentWillReceiveProps(
objectnextProps
)
componentWillReceiveProps(objectnextProps)
```
Invoked when a component is receiving new props. This method is not called for the initial render.
If `shouldComponentUpdate` returns false, then `render()` will be completely skipped until the next state change. In addition, `componentWillUpdate` and `componentDidUpdate` will not be called.
If `shouldComponentUpdate` returns false, then `render()` will be completely skipped until the next state change. (In addition, `componentWillUpdate` and `componentDidUpdate` will not be called.)
By default, `shouldComponentUpdate` always returns `true` to prevent subtle bugs when `state` is mutated in place, but if you are careful to always treat `state` as immutable and to read only from `props` and `state` in `render()` then you can override `shouldComponentUpdate` with an implementation that compares the old props and state to their replacements.
By default, `shouldComponentUpdate` always returns true to prevent subtle bugs when `state` is mutated in place, but if you are careful to always treat `state` as immutable and to read only from `props` and `state` in `render()` then you can override `shouldComponentUpdate` with an implementation that compares the old props and state to their replacements.
If performance is a bottleneck, especially with dozens or hundreds of components, use `shouldComponentUpdate` to speed up your app.
@@ -180,9 +176,7 @@ If performance is a bottleneck, especially with dozens or hundreds of components
React attempts to support all common elements. If you need an element that isn't listed here, please [file an issue](https://github.com/facebook/react/issues/new).
React attempts to support all common elements. If you need an element that isn't listed here, please file an issue.
### HTML Elements
@@ -53,16 +53,17 @@ These standard attributes are supported:
```
accept acceptCharset accessKey action allowFullScreen allowTransparency alt
> As of v0.12, returning `false` from an event handler will no longer stop event propagation. Instead, `e.stopPropagation()` or `e.preventDefault()` should be triggered manually, as appropriate.
## Event pooling
The `SyntheticEvent` is pooled. This means that the `SyntheticEvent` object will be reused and all properties will be nullified after the event callback has been invoked.
This is for performance reasons.
As such, you cannot access the event in an asynchronous way.
```javascript
functiononClick(event){
console.log(event);// => nullified object.
console.log(event.type);// => "click"
vareventType=event.type;// => "click"
setTimeout(function(){
console.log(event.type);// => null
console.log(eventType);// => "click"
},0);
this.setState({clickEvent:event});// Won't work. this.state.clickEvent will only contain null values.
this.setState({eventType:event.type});// You can still export event properties.
}
```
> Note:
>
> If you want to access the event properties in an asynchronous way, you should call `event.persist()` on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
## Supported Events
React normalizes events so that they have consistent properties across
different browsers.
different browsers.
The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append `Capture` to the event name; for example, instead of using `onClick`, you would use `onClickCapture` to handle the click event in the capture phase.
@@ -168,9 +143,6 @@ boolean shiftKey
### Touch events
To enable touch events, call `React.initializeTouchEvents(true)` before
A `ReactElement`-factory is simply a function that generates a `ReactElement` with a particular `type` property. React has a built-in helper for you to create factories. It's effectively just:
@@ -105,7 +105,7 @@ When this constructor is invoked it is expected to return an object with at leas
varcomponent=newMyComponent(props);// never do this
```
Other than for testing, you would normally *never* call this constructor yourself. React calls it for you.
Other than for testing, you would normally __never__ call this constructor yourself. React calls it for you.
Instead, you pass the `ReactComponent` Class to `createElement` you get a `ReactElement`.
@@ -140,13 +140,13 @@ The `render` method of a `ReactComponent` is expected to return another `ReactEl
@@ -25,37 +25,35 @@ It'll also have a few neat features:
### Running a server
In order to start this tutorial, we're going to require a running server. This will serve purely as an API endpoint which we'll use for getting and saving data. In order to make this as easy as possible, we've created a simple server in a number of scripting languages that does exactly what we need it to do. **You can [view the source](https://github.com/reactjs/react-tutorial/) or [download a zip file](https://github.com/reactjs/react-tutorial/archive/master.zip) containing everything needed to get started.**
While it's not necessary to get started with this tutorial, later on we'll be adding functionality that requires `POST`ing to a running server. If this is something you are intimately familiar with and want to create your own server, please do. For the rest of you who might want to focus on learning about React without having to worry about the server-side aspects, we have written simple servers in a number of languages - JavaScript (using Node.js), Python, Ruby, Go, and PHP. These are all available on GitHub. You can [view the source](https://github.com/reactjs/react-tutorial/) or [download a zip file](https://github.com/reactjs/react-tutorial/archive/master.zip) to get started.
For sake of simplicity, the server we will run uses a `JSON` file as a database. You would not run this in production but it makes it easy to simulate what you might do when consuming an API. Once you start the server, it will support our API endpoint and it will also serve the static pages we need.
To get started using the tutorial, just start editing `public/index.html`.
### Getting started
For this tutorial, we're going to make it as easy as possible. Included in the server package discussed above is an HTML file which we'll work in. Open up `public/index.html` in your favorite editor. It should look something like this (with perhaps some minor differences, we'll add an additional `<script>` tag later):
For this tutorial, we'll use prebuilt JavaScript files on a CDN. Open up `public/index.html` in your favorite editor, which should contain the following:
// To get started with this tutorial running your own code, simply remove
// the script tag loading scripts/example.js and start writing code here.
<scripttype="text/jsx">
// Your code here
</script>
</body>
</html>
```
For the remainder of this tutorial, we'll be writing our JavaScript code in this script tag. We don't have any advanced live-reloading so you'll need to refresh your browser to see updates after saving. Follow your progress by opening `http://localhost:3000` in your browser (after starting the server). When you load this for the first time without any changes, you'll see the finished product of what we're going to build. When you're ready to start working, just delete the preceding `<script>` tag and then you can continue.
For the remainder of this tutorial, we'll be writing our JavaScript code in this script tag. Follow your progress by opening your index.html file in your browser after each addition.
> Note:
>
@@ -223,10 +221,10 @@ First, add the third-party library **marked** to your application. This is a Jav
@@ -346,15 +340,13 @@ Let's replace the hard-coded data with some dynamic data from the server. We wil
```javascript{3}
// tutorial11.js
React.render(
<CommentBox url="/api/comments" />,
<CommentBox url="comments.json" />,
document.getElementById('content')
);
```
This component is different from the prior components because it will have to re-render itself. The component won't have any data until the request from the server comes back, at which point the component may need to render some new comments.
Note: the code will not be working at this step.
### Reactive state
So far, based on its props, each component has rendered itself once. `props` are immutable: they are passed from the parent and are "owned" by the parent. To implement interactions, we introduce mutable **state** to the component. `this.state` is private to the component and can be changed by calling `this.setState()`. When the state updates, the component re-renders itself.
@@ -384,15 +376,20 @@ var CommentBox = React.createClass({
`getInitialState()` executes exactly once during the lifecycle of the component and sets up the initial state of the component.
#### Updating state
When the component is first created, we want to GET some JSON from the server and update the state to reflect the latest data. We're going to use jQuery to make an asynchronous request to the server we started earlier to fetch the data we need. It will look something like this:
When the component is first created, we want to GET some JSON from the server and update the state to reflect the latest data. In a real application this would be a dynamic endpoint, but for this example we will keep things simple by creating a static JSON file `public/comments.json` containing the array of comments:
```json
```javascript
// tutorial13.json
[
{"author": "Pete Hunt", "text": "This is one comment"},
{"author": "Jordan Walke", "text": "This is *another* comment"}
]
```
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. [As mentioned above](#running-a-server), we have provided several servers you can use [on GitHub](https://github.com/reactjs/react-tutorial/). They provide the functionality you need for the rest of this tutorial.
```javascript{6-18}
// tutorial13.js
var CommentBox = React.createClass({
@@ -461,13 +458,13 @@ 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 2 seconds after that. Try running this in your browser and changing the `comments.json` file (in the same directory as your server); within 2 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!
All scripts are also available via [CDNJS](https://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:
Many members of the community use Stack Overflow to ask questions. Read through the [existing questions](http://stackoverflow.com/questions/tagged/reactjs) tagged with **reactjs** or [ask your own](http://stackoverflow.com/questions/ask?tags=reactjs)!
Many members of the community use Stack Overflow to ask questions. Read through the [existing questions](http://stackoverflow.com/questions/tagged/reactjs) tagged with **reactjs** or [ask your own](http://stackoverflow.com/questions/ask)!
## Discussion forum
@@ -22,6 +22,6 @@ Many developers and users idle on Freenode.net's IRC network in **[#reactjs on f
## Twitter
For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs). In addition, you can use the #reactjs hashtag to see what others are saying or add to the conversation.
For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs). In addition, you can use the [**#reactjs** hashtag](https://twitter.com/search?q=%23reactjs) to keep up with the latest React news.
> In the example above, an ES6 [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) is utilized to lexically bind the value of `this`.
Try using it today with the [Babel REPL](https://babeljs.io/repl/).
Try using it today with the [JSX compiler](/react/jsx-compiler.html).
This is a dummy npm package that allows us to treat it as an eslint-plugin. It's not actually published, nor are the rules here useful for users of react. If you want to lint your react code, try <https://github.com/yannickcr/eslint-plugin-react>.
**If you modify this rule, you must re-run `npm install ./eslint-rules` for it to take effect.**
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.