diff --git a/blog/2013/06/02/jsfiddle-integration.html b/blog/2013/06/02/jsfiddle-integration.html index d1aa66bcd5..f0c3bd965b 100644 --- a/blog/2013/06/02/jsfiddle-integration.html +++ b/blog/2013/06/02/jsfiddle-integration.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/06/05/why-react.html b/blog/2013/06/05/why-react.html index 48ae755f75..774cebf012 100644 --- a/blog/2013/06/05/why-react.html +++ b/blog/2013/06/05/why-react.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/06/12/community-roundup.html b/blog/2013/06/12/community-roundup.html index f384deafcb..ea1b1b6657 100644 --- a/blog/2013/06/12/community-roundup.html +++ b/blog/2013/06/12/community-roundup.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/06/19/community-roundup-2.html b/blog/2013/06/19/community-roundup-2.html index 727c2086c7..5d2de76ddd 100644 --- a/blog/2013/06/19/community-roundup-2.html +++ b/blog/2013/06/19/community-roundup-2.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/06/21/react-v0-3-3.html b/blog/2013/06/21/react-v0-3-3.html index 31dbe025bc..5d5ec1246b 100644 --- a/blog/2013/06/21/react-v0-3-3.html +++ b/blog/2013/06/21/react-v0-3-3.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/06/27/community-roundup-3.html b/blog/2013/06/27/community-roundup-3.html index a35b1296c7..6a3e39ae1c 100644 --- a/blog/2013/06/27/community-roundup-3.html +++ b/blog/2013/06/27/community-roundup-3.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/07/02/react-v0-4-autobind-by-default.html b/blog/2013/07/02/react-v0-4-autobind-by-default.html index 7e97c67ee5..5fcd6ae669 100644 --- a/blog/2013/07/02/react-v0-4-autobind-by-default.html +++ b/blog/2013/07/02/react-v0-4-autobind-by-default.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/07/03/community-roundup-4.html b/blog/2013/07/03/community-roundup-4.html index e607f890af..65cf213c2e 100644 --- a/blog/2013/07/03/community-roundup-4.html +++ b/blog/2013/07/03/community-roundup-4.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/07/11/react-v0-4-prop-validation-and-default-values.html b/blog/2013/07/11/react-v0-4-prop-validation-and-default-values.html index 64c8f400a1..7c8fa216e2 100644 --- a/blog/2013/07/11/react-v0-4-prop-validation-and-default-values.html +++ b/blog/2013/07/11/react-v0-4-prop-validation-and-default-values.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/07/17/react-v0-4-0.html b/blog/2013/07/17/react-v0-4-0.html index 7a5a09dced..a623932e1c 100644 --- a/blog/2013/07/17/react-v0-4-0.html +++ b/blog/2013/07/17/react-v0-4-0.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/07/23/community-roundup-5.html b/blog/2013/07/23/community-roundup-5.html index 702539ad94..f6b439c2e2 100644 --- a/blog/2013/07/23/community-roundup-5.html +++ b/blog/2013/07/23/community-roundup-5.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/07/26/react-v0-4-1.html b/blog/2013/07/26/react-v0-4-1.html index 5be3fb78a8..bf5dc0b17b 100644 --- a/blog/2013/07/26/react-v0-4-1.html +++ b/blog/2013/07/26/react-v0-4-1.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/07/30/use-react-and-jsx-in-ruby-on-rails.html b/blog/2013/07/30/use-react-and-jsx-in-ruby-on-rails.html index c5d6649c57..e10215a350 100644 --- a/blog/2013/07/30/use-react-and-jsx-in-ruby-on-rails.html +++ b/blog/2013/07/30/use-react-and-jsx-in-ruby-on-rails.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/08/05/community-roundup-6.html b/blog/2013/08/05/community-roundup-6.html index 4c5f04cefe..3e91751133 100644 --- a/blog/2013/08/05/community-roundup-6.html +++ b/blog/2013/08/05/community-roundup-6.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/08/19/use-react-and-jsx-in-python-applications.html b/blog/2013/08/19/use-react-and-jsx-in-python-applications.html index 7ac7457380..a98bd141ea 100644 --- a/blog/2013/08/19/use-react-and-jsx-in-python-applications.html +++ b/blog/2013/08/19/use-react-and-jsx-in-python-applications.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/08/26/community-roundup-7.html b/blog/2013/08/26/community-roundup-7.html index 6b5c11eeda..361585ad68 100644 --- a/blog/2013/08/26/community-roundup-7.html +++ b/blog/2013/08/26/community-roundup-7.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/09/24/community-roundup-8.html b/blog/2013/09/24/community-roundup-8.html index 4b268a5622..1efb1710f5 100644 --- a/blog/2013/09/24/community-roundup-8.html +++ b/blog/2013/09/24/community-roundup-8.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/10/03/community-roundup-9.html b/blog/2013/10/03/community-roundup-9.html index 9f617a01c5..22d520e238 100644 --- a/blog/2013/10/03/community-roundup-9.html +++ b/blog/2013/10/03/community-roundup-9.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/10/16/react-v0.5.0.html b/blog/2013/10/16/react-v0.5.0.html index bed2c0e014..bb60fe6431 100644 --- a/blog/2013/10/16/react-v0.5.0.html +++ b/blog/2013/10/16/react-v0.5.0.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/10/29/react-v0-5-1.html b/blog/2013/10/29/react-v0-5-1.html index c5c3eaf2cb..8e3d8822d6 100644 --- a/blog/2013/10/29/react-v0-5-1.html +++ b/blog/2013/10/29/react-v0-5-1.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/11/05/thinking-in-react.html b/blog/2013/11/05/thinking-in-react.html index 2c05f06102..55c0f806e6 100644 --- a/blog/2013/11/05/thinking-in-react.html +++ b/blog/2013/11/05/thinking-in-react.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/11/06/community-roundup-10.html b/blog/2013/11/06/community-roundup-10.html index f43b903092..1fb9b67eb7 100644 --- a/blog/2013/11/06/community-roundup-10.html +++ b/blog/2013/11/06/community-roundup-10.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/11/18/community-roundup-11.html b/blog/2013/11/18/community-roundup-11.html index a85b39b536..13db6abc2c 100644 --- a/blog/2013/11/18/community-roundup-11.html +++ b/blog/2013/11/18/community-roundup-11.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/12/18/react-v0.5.2-v0.4.2.html b/blog/2013/12/18/react-v0.5.2-v0.4.2.html index 6ac56e6b08..ac2446f59c 100644 --- a/blog/2013/12/18/react-v0.5.2-v0.4.2.html +++ b/blog/2013/12/18/react-v0.5.2-v0.4.2.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/12/19/react-v0.8.0.html b/blog/2013/12/19/react-v0.8.0.html index 2ee9714ee6..93fa842560 100644 --- a/blog/2013/12/19/react-v0.8.0.html +++ b/blog/2013/12/19/react-v0.8.0.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/12/23/community-roundup-12.html b/blog/2013/12/23/community-roundup-12.html index 60bbbc60ef..f0132e98b3 100644 --- a/blog/2013/12/23/community-roundup-12.html +++ b/blog/2013/12/23/community-roundup-12.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2013/12/30/community-roundup-13.html b/blog/2013/12/30/community-roundup-13.html index 8ecd1d4012..6ca0708ba5 100644 --- a/blog/2013/12/30/community-roundup-13.html +++ b/blog/2013/12/30/community-roundup-13.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/01/02/react-chrome-developer-tools.html b/blog/2014/01/02/react-chrome-developer-tools.html index 38f9ae7e8a..6735d40b08 100644 --- a/blog/2014/01/02/react-chrome-developer-tools.html +++ b/blog/2014/01/02/react-chrome-developer-tools.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/01/06/community-roundup-14.html b/blog/2014/01/06/community-roundup-14.html index 719e14ee22..4c0cc659f7 100644 --- a/blog/2014/01/06/community-roundup-14.html +++ b/blog/2014/01/06/community-roundup-14.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/02/05/community-roundup-15.html b/blog/2014/02/05/community-roundup-15.html index 87d8a2c165..82cb4243fd 100644 --- a/blog/2014/02/05/community-roundup-15.html +++ b/blog/2014/02/05/community-roundup-15.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/02/15/community-roundup-16.html b/blog/2014/02/15/community-roundup-16.html index 2f333fe092..5536616154 100644 --- a/blog/2014/02/15/community-roundup-16.html +++ b/blog/2014/02/15/community-roundup-16.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/02/16/react-v0.9-rc1.html b/blog/2014/02/16/react-v0.9-rc1.html index 8a89e36564..4f3cb05c0e 100644 --- a/blog/2014/02/16/react-v0.9-rc1.html +++ b/blog/2014/02/16/react-v0.9-rc1.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/02/20/react-v0.9.html b/blog/2014/02/20/react-v0.9.html index be3b620cfc..de460dcdd3 100644 --- a/blog/2014/02/20/react-v0.9.html +++ b/blog/2014/02/20/react-v0.9.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/02/24/community-roundup-17.html b/blog/2014/02/24/community-roundup-17.html index f97844dbd7..c89f6f9695 100644 --- a/blog/2014/02/24/community-roundup-17.html +++ b/blog/2014/02/24/community-roundup-17.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/03/14/community-roundup-18.html b/blog/2014/03/14/community-roundup-18.html index be5c1572aa..f90234b59e 100644 --- a/blog/2014/03/14/community-roundup-18.html +++ b/blog/2014/03/14/community-roundup-18.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/03/19/react-v0.10-rc1.html b/blog/2014/03/19/react-v0.10-rc1.html index a2765b5626..c02fc6eb0a 100644 --- a/blog/2014/03/19/react-v0.10-rc1.html +++ b/blog/2014/03/19/react-v0.10-rc1.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/03/21/react-v0.10.html b/blog/2014/03/21/react-v0.10.html index dd4ed0d5a7..0c354eb53c 100644 --- a/blog/2014/03/21/react-v0.10.html +++ b/blog/2014/03/21/react-v0.10.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/03/28/the-road-to-1.0.html b/blog/2014/03/28/the-road-to-1.0.html index 5dca4dd1fd..2724a784a6 100644 --- a/blog/2014/03/28/the-road-to-1.0.html +++ b/blog/2014/03/28/the-road-to-1.0.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/04/04/reactnet.html b/blog/2014/04/04/reactnet.html index a4e92bf045..79fa210679 100644 --- a/blog/2014/04/04/reactnet.html +++ b/blog/2014/04/04/reactnet.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/05/06/flux.html b/blog/2014/05/06/flux.html index ed96ce7523..21cf9be453 100644 --- a/blog/2014/05/06/flux.html +++ b/blog/2014/05/06/flux.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/05/29/one-year-of-open-source-react.html b/blog/2014/05/29/one-year-of-open-source-react.html index 34c9f1cac5..74d3473129 100644 --- a/blog/2014/05/29/one-year-of-open-source-react.html +++ b/blog/2014/05/29/one-year-of-open-source-react.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/06/27/community-roundup-19.html b/blog/2014/06/27/community-roundup-19.html index 081f1a16f5..18b733d0ae 100644 --- a/blog/2014/06/27/community-roundup-19.html +++ b/blog/2014/06/27/community-roundup-19.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/07/13/react-v0.11-rc1.html b/blog/2014/07/13/react-v0.11-rc1.html index c84b42b603..01bc5b4bd4 100644 --- a/blog/2014/07/13/react-v0.11-rc1.html +++ b/blog/2014/07/13/react-v0.11-rc1.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/07/17/react-v0.11.html b/blog/2014/07/17/react-v0.11.html index cd3ceefd68..7e76497c08 100644 --- a/blog/2014/07/17/react-v0.11.html +++ b/blog/2014/07/17/react-v0.11.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/07/25/react-v0.11.1.html b/blog/2014/07/25/react-v0.11.1.html index a8cd77bf01..57f101d596 100644 --- a/blog/2014/07/25/react-v0.11.1.html +++ b/blog/2014/07/25/react-v0.11.1.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/07/28/community-roundup-20.html b/blog/2014/07/28/community-roundup-20.html index 3465a06fae..4abf6898a6 100644 --- a/blog/2014/07/28/community-roundup-20.html +++ b/blog/2014/07/28/community-roundup-20.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/07/30/flux-actions-and-the-dispatcher.html b/blog/2014/07/30/flux-actions-and-the-dispatcher.html index a6a34c2336..4d85345f6e 100644 --- a/blog/2014/07/30/flux-actions-and-the-dispatcher.html +++ b/blog/2014/07/30/flux-actions-and-the-dispatcher.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/08/03/community-roundup-21.html b/blog/2014/08/03/community-roundup-21.html index f16410900b..2f92bddcb5 100644 --- a/blog/2014/08/03/community-roundup-21.html +++ b/blog/2014/08/03/community-roundup-21.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/09/03/introducing-the-jsx-specification.html b/blog/2014/09/03/introducing-the-jsx-specification.html index c61c9aa51f..f4c8b7ce00 100644 --- a/blog/2014/09/03/introducing-the-jsx-specification.html +++ b/blog/2014/09/03/introducing-the-jsx-specification.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/09/12/community-round-up-22.html b/blog/2014/09/12/community-round-up-22.html index a6fa8e6c5c..9730b8334f 100644 --- a/blog/2014/09/12/community-round-up-22.html +++ b/blog/2014/09/12/community-round-up-22.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/09/16/react-v0.11.2.html b/blog/2014/09/16/react-v0.11.2.html index fb06d42180..6bbc5e3d8d 100644 --- a/blog/2014/09/16/react-v0.11.2.html +++ b/blog/2014/09/16/react-v0.11.2.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/09/24/testing-flux-applications.html b/blog/2014/09/24/testing-flux-applications.html new file mode 100644 index 0000000000..05e8b80cc4 --- /dev/null +++ b/blog/2014/09/24/testing-flux-applications.html @@ -0,0 +1,398 @@ + + + + + + + Testing Flux Applications | React + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+ + +
+

Testing Flux Applications

+

September 24, 2014 by Bill Fisher

+ +
+ +
+

Flux is the application architecture that Facebook uses to build web applications with React. It's based on a unidirectional data flow. In previous blog posts and documentation articles, we've shown the basic structure and data flow, more closely examined the dispatcher and action creators, and shown how to put it all together with a tutorial. Now let's look at how to do formal unit testing of Flux applications with Jest, Facebook's auto-mocking testing framework.

+

Testing with Jest #

+

For a unit test to operate on a truly isolated unit of the application, we need to mock every module except the one we are testing. Jest makes the mocking of other parts of a Flux application trivial. To illustrate testing with Jest, we'll return to our example TodoMVC application.

+ +

The first steps toward working with Jest are as follows:

+ +
    +
  1. Get the module depencies for the application installed by running npm install.
  2. +
  3. Create a directory __tests__/ with a test file, in this case TodoStore-test.js
  4. +
  5. Run npm install jest-cli —save-dev
  6. +
  7. Add the following to your package.json
  8. +
+
{
+  ...
+  "scripts": {
+    "test": "jest"
+  }
+  ...
+}
+
+

Now you're ready to run your tests from the command line with npm test.

+ +

By default, all modules are mocked, so the only boilerplate we need in TodoStore-test.js is a declarative call to Jest's dontMock() method.

+
jest.dontMock('TodoStore');
+
+

This tells Jest to let TodoStore be a real object with real, live methods. Jest will mock all other objects involved with the test.

+

Testing Stores #

+

At Facebook, Flux stores often receive a great deal of formal unit test coverage, as this is where the application state and logic lives. Stores are arguably the most important place in a Flux application to provide coverage, but at first glance, it's not entirely obvious how to test them.

+ +

By design, stores can't be modified from the outside. They have no setters. The only way new data can enter a store is through the callback it registers with the dispatcher.

+ +

We therefore need to simulate the Flux data flow with this one weird trick.

+
var mockRegister = MyDispatcher.register;
+var mockRegisterInfo = mockRegister.mock;
+var callsToRegister = mockRegisterInfo.calls;
+var firstCall = callsToRegister[0];
+var firstArgument = firstCall[0];
+var callback = firstArgument;
+
+

We now have the store's registered callback, the sole mechanism by which data can enter the store.

+ +

For folks new to Jest, or mocks in general, it might not be entirely obvious what is happening in that code block, so let's look at each part of it a bit more closely. We start out by looking at the register() method of our application's dispatcher — the method that the store uses to register its callback with the dispatcher. The dispatcher has been thoroughly mocked automatically by Jest, so we can get a reference to the mocked version of the register() method just as we would normally refer to that method in our production code. But we can get additional information about that method with the mock property of that method. We don't often think of methods having properties, but in Jest, this idea is vital. Every method of a mocked object has this property, and it allows us to examine how the method is being called during the test. A chronologically ordered list of calls to register() is available with the calls property of mock, and each of these calls has a list of the arguments that were used in each method call.

+ +

So in this code, we are really saying, "Give me a reference to the first argument of the first call to MyDispatcher's register() method." That first argument is the store's callback, so now we have all we need to start testing. But first, we can save ourselves some semicolons and roll all of this into a single line:

+
callback = MyDispatcher.register.mock.calls[0][0];
+
+

We can invoke that callback whenever we like, independent of our application's dispatcher or action creators. We will, in fact, fake the behavior of the dispatcher and action creators by invoking the callback with an action that we'll create directly in our test.

+
var payload = {
+  source: 'VIEW_ACTION',
+  action: {
+    actionType: TodoConstants.TODO_CREATE,
+    text: 'foo'
+  }
+};
+callback(payload);
+var all = TodoStore.getAll();
+var keys = Object.keys(all);
+expect(all[keys[0]].text).toEqual('foo');
+

Puting it All Together #

+

The example Flux TodoMVC application has been updated with an example test for the TodoStore, but lets's look at an abbreviated version of the entire test. The most important things to notice in this test are how we keep a reference to the store's registered callback in the closure of the test, and how we recreate the store before every test so that we clear the state of the store entirely.

+
jest.dontMock('../TodoStore');
+jest.dontMock('react/lib/merge');
+
+describe('TodoStore', function() {
+
+  var TodoConstants = require('../../constants/TodoConstants');
+
+  // mock actions inside dispatch payloads
+  var actionTodoCreate = {
+    source: 'VIEW_ACTION',
+    action: {
+      actionType: TodoConstants.TODO_CREATE,
+      text: 'foo'
+    }
+  };
+  var actionTodoDestroy = {
+    source: 'VIEW_ACTION',
+    action: {
+      actionType: TodoConstants.TODO_DESTROY,
+      id: 'replace me in test'
+    }
+  };
+
+  var AppDispatcher;
+  var TodoStore;
+  var callback;
+
+  beforeEach(function() {
+    AppDispatcher = require('../../dispatcher/AppDispatcher');
+    TodoStore = require('../TodoStore');
+    callback = AppDispatcher.register.mock.calls[0][0];
+  });
+
+  it('registers a callback with the dispatcher', function() {
+    expect(AppDispatcher.register.mock.calls.length).toBe(1);
+  });
+
+  it('initializes with no to-do items', function() {
+    var all = TodoStore.getAll();
+    expect(all).toEqual({});
+  });
+
+  it('creates a to-do item', function() {
+    callback(actionTodoCreate);
+    var all = TodoStore.getAll();
+    var keys = Object.keys(all);
+    expect(keys.length).toBe(1);
+    expect(all[keys[0]].text).toEqual('foo');
+  });
+
+  it('destroys a to-do item', function() {
+    callback(actionTodoCreate);
+    var all = TodoStore.getAll();
+    var keys = Object.keys(all);
+    expect(keys.length).toBe(1);
+    actionTodoDestroy.action.id = keys[0];
+    callback(actionTodoDestroy);
+    expect(all[keys[0]]).toBeUndefined();
+  });
+
+});
+
+

You can take a look at all this code in the TodoStore's tests on GitHub as well.

+

Mocking Data Derived from Other Stores #

+

Sometimes our stores rely on data from other stores. Because all of our modules are mocked, we'll need to simulate the data that comes from the other store. We can do this by retrieving the mock function and adding a custom return value to it.

+
var MyOtherStore = require('../MyOtherStore');
+MyOtherStore.getState.mockReturnValue({
+  '123': {
+    id: '123',
+    text: 'foo'
+  },
+  '456': {
+    id: '456',
+    text: 'bar'
+  }
+});
+
+

Now we have a collection of objects that will come back from MyOtherStore whenever we call MyOtherStore.getState() in our tests. Any application state can be simulated with a combination of these custom return values and the previously shown technique of working with the store's registered callback.

+ +

A brief example of this technique is up on GitHub within the Flux Chat example's UnreadThreadStore-test.js.

+ +

For more information about the mock property of mocked methods or Jest's ability to provide custom mock values, see Jest's documentation on mock functions.

+

Moving Logic from React to Stores #

+

What often starts as a little piece of seemingly benign logic in our React components often presents a problem while creating unit tests. We want to be able to write tests that read like a specification for our application's behavior, and when application logic slips into our view layer, this becomes more difficult.

+ +

For example, when a user has marked each of their to-do items as complete, the TodoMVC specification dictates that we should also change the status of the "Mark all as complete" checkbox automatically. To create that logic, we might be tempted to write code like this in our MainSection's render() method:

+
var allTodos = this.props.allTodos;
+var allChecked = true;
+for (var id in allTodos) {
+  if (!allTodos[id].complete) {
+    allChecked = false;
+    break;
+  }
+}
+...
+
+return (
+  <section id="main">
+  <input
+    id="toggle-all"
+    type="checkbox"
+    checked={allChecked ? 'checked' : ''}
+  />
+  ...
+  </section>
+);
+
+

While this seems like an easy, normal thing to do, this is an example of application logic slipping into the views, and it can't be described in our spec-style TodoStore test. Let's take that logic and move it to the store. First, we'll create a public method on the store that will encapsulate that logic:

+
areAllComplete: function() {
+  for (var id in _todos) {
+    if (!_todos[id].complete) {
+      return false;
+    }
+  }
+  return true;
+},
+
+

Now we have the application logic where it belongs, and we can write the following test:

+
it('determines whether all to-do items are complete', function() {
+  var i = 0;
+  for (; i < 3; i++) {
+    callback(mockTodoCreate);
+  }
+  expect(TodoStore.areAllComplete()).toBe(false);
+
+  var all = TodoStore.getAll();
+  for (key in all) {
+    callback({
+      source: 'VIEW_ACTION',
+      action: {
+        actionType: TodoConstants.TODO_COMPLETE,
+        id: key
+      }
+    });
+  }
+  expect(TodoStore.areAllComplete()).toBe(true);
+
+  callback({
+    source: 'VIEW_ACTION',
+    action: {
+      actionType: TodoConstants.TODO_UNDO_COMPLETE,
+      id: key
+    }
+  });
+  expect(TodoStore.areAllComplete()).toBe(false);
+});
+
+

Finally, we revise our view layer. We'll call for that data in the controller-view, TodoApp.js, and pass it down to the MainSection component.

+
function getTodoState() {
+  return {
+    allTodos: TodoStore.getAll(),
+    areAllComplete: TodoStore.areAllComplete()
+  };
+}
+
+var TodoApp = React.createClass({
+...
+
+  /**
+   * @return {object}
+   */
+  render: function() {
+    return (
+      ...
+      <MainSection
+        allTodos={this.state.allTodos}
+        areAllComplete={this.state.areAllComplete}
+      />
+      ...
+    );
+  },
+
+  /**
+   * Event handler for 'change' events coming from the TodoStore
+   */
+  _onChange: function() {
+    this.setState(getTodoState());
+  }
+
+});
+
+

And then we'll utilize that property for the rendering of the checkbox.

+
render: function() {
+  ...
+
+  return (
+    <section id="main">
+    <input
+      id="toggle-all"
+      type="checkbox"
+      checked={this.props.areAllComplete ? 'checked' : ''}
+    />
+    ...
+    </section>
+  );
+},
+
+

To learn how to test React components themselves, check out the Jest tutorial for React and the ReactTestUtils documenation.

+

Further Reading #

+ + +
+ +
+
+
+ + + +
+
+ + + + diff --git a/blog/all.html b/blog/all.html index 0719645153..edfb0c860d 100644 --- a/blog/all.html +++ b/blog/all.html @@ -61,6 +61,8 @@

All Posts

+

Testing Flux Applications on September 24, 2014 by Bill Fisher

+

React v0.11.2 on September 16, 2014 by Paul O’Shannessy

Community Round-up #22 on September 12, 2014 by Lou Husson

diff --git a/blog/index.html b/blog/index.html index 991d742541..98a1dd5bf7 100644 --- a/blog/index.html +++ b/blog/index.html @@ -63,6 +63,8 @@

Recent posts

@@ -90,6 +90,278 @@

Recent posts

+
+

Testing Flux Applications

+

September 24, 2014 by Bill Fisher

+
+
+

Flux is the application architecture that Facebook uses to build web applications with React. It's based on a unidirectional data flow. In previous blog posts and documentation articles, we've shown the basic structure and data flow, more closely examined the dispatcher and action creators, and shown how to put it all together with a tutorial. Now let's look at how to do formal unit testing of Flux applications with Jest, Facebook's auto-mocking testing framework.

+

Testing with Jest #

+

For a unit test to operate on a truly isolated unit of the application, we need to mock every module except the one we are testing. Jest makes the mocking of other parts of a Flux application trivial. To illustrate testing with Jest, we'll return to our example TodoMVC application.

+ +

The first steps toward working with Jest are as follows:

+ +
    +
  1. Get the module depencies for the application installed by running npm install.
  2. +
  3. Create a directory __tests__/ with a test file, in this case TodoStore-test.js
  4. +
  5. Run npm install jest-cli —save-dev
  6. +
  7. Add the following to your package.json
  8. +
+
{
+  ...
+  "scripts": {
+    "test": "jest"
+  }
+  ...
+}
+
+

Now you're ready to run your tests from the command line with npm test.

+ +

By default, all modules are mocked, so the only boilerplate we need in TodoStore-test.js is a declarative call to Jest's dontMock() method.

+
jest.dontMock('TodoStore');
+
+

This tells Jest to let TodoStore be a real object with real, live methods. Jest will mock all other objects involved with the test.

+

Testing Stores #

+

At Facebook, Flux stores often receive a great deal of formal unit test coverage, as this is where the application state and logic lives. Stores are arguably the most important place in a Flux application to provide coverage, but at first glance, it's not entirely obvious how to test them.

+ +

By design, stores can't be modified from the outside. They have no setters. The only way new data can enter a store is through the callback it registers with the dispatcher.

+ +

We therefore need to simulate the Flux data flow with this one weird trick.

+
var mockRegister = MyDispatcher.register;
+var mockRegisterInfo = mockRegister.mock;
+var callsToRegister = mockRegisterInfo.calls;
+var firstCall = callsToRegister[0];
+var firstArgument = firstCall[0];
+var callback = firstArgument;
+
+

We now have the store's registered callback, the sole mechanism by which data can enter the store.

+ +

For folks new to Jest, or mocks in general, it might not be entirely obvious what is happening in that code block, so let's look at each part of it a bit more closely. We start out by looking at the register() method of our application's dispatcher — the method that the store uses to register its callback with the dispatcher. The dispatcher has been thoroughly mocked automatically by Jest, so we can get a reference to the mocked version of the register() method just as we would normally refer to that method in our production code. But we can get additional information about that method with the mock property of that method. We don't often think of methods having properties, but in Jest, this idea is vital. Every method of a mocked object has this property, and it allows us to examine how the method is being called during the test. A chronologically ordered list of calls to register() is available with the calls property of mock, and each of these calls has a list of the arguments that were used in each method call.

+ +

So in this code, we are really saying, "Give me a reference to the first argument of the first call to MyDispatcher's register() method." That first argument is the store's callback, so now we have all we need to start testing. But first, we can save ourselves some semicolons and roll all of this into a single line:

+
callback = MyDispatcher.register.mock.calls[0][0];
+
+

We can invoke that callback whenever we like, independent of our application's dispatcher or action creators. We will, in fact, fake the behavior of the dispatcher and action creators by invoking the callback with an action that we'll create directly in our test.

+
var payload = {
+  source: 'VIEW_ACTION',
+  action: {
+    actionType: TodoConstants.TODO_CREATE,
+    text: 'foo'
+  }
+};
+callback(payload);
+var all = TodoStore.getAll();
+var keys = Object.keys(all);
+expect(all[keys[0]].text).toEqual('foo');
+

Puting it All Together #

+

The example Flux TodoMVC application has been updated with an example test for the TodoStore, but lets's look at an abbreviated version of the entire test. The most important things to notice in this test are how we keep a reference to the store's registered callback in the closure of the test, and how we recreate the store before every test so that we clear the state of the store entirely.

+
jest.dontMock('../TodoStore');
+jest.dontMock('react/lib/merge');
+
+describe('TodoStore', function() {
+
+  var TodoConstants = require('../../constants/TodoConstants');
+
+  // mock actions inside dispatch payloads
+  var actionTodoCreate = {
+    source: 'VIEW_ACTION',
+    action: {
+      actionType: TodoConstants.TODO_CREATE,
+      text: 'foo'
+    }
+  };
+  var actionTodoDestroy = {
+    source: 'VIEW_ACTION',
+    action: {
+      actionType: TodoConstants.TODO_DESTROY,
+      id: 'replace me in test'
+    }
+  };
+
+  var AppDispatcher;
+  var TodoStore;
+  var callback;
+
+  beforeEach(function() {
+    AppDispatcher = require('../../dispatcher/AppDispatcher');
+    TodoStore = require('../TodoStore');
+    callback = AppDispatcher.register.mock.calls[0][0];
+  });
+
+  it('registers a callback with the dispatcher', function() {
+    expect(AppDispatcher.register.mock.calls.length).toBe(1);
+  });
+
+  it('initializes with no to-do items', function() {
+    var all = TodoStore.getAll();
+    expect(all).toEqual({});
+  });
+
+  it('creates a to-do item', function() {
+    callback(actionTodoCreate);
+    var all = TodoStore.getAll();
+    var keys = Object.keys(all);
+    expect(keys.length).toBe(1);
+    expect(all[keys[0]].text).toEqual('foo');
+  });
+
+  it('destroys a to-do item', function() {
+    callback(actionTodoCreate);
+    var all = TodoStore.getAll();
+    var keys = Object.keys(all);
+    expect(keys.length).toBe(1);
+    actionTodoDestroy.action.id = keys[0];
+    callback(actionTodoDestroy);
+    expect(all[keys[0]]).toBeUndefined();
+  });
+
+});
+
+

You can take a look at all this code in the TodoStore's tests on GitHub as well.

+

Mocking Data Derived from Other Stores #

+

Sometimes our stores rely on data from other stores. Because all of our modules are mocked, we'll need to simulate the data that comes from the other store. We can do this by retrieving the mock function and adding a custom return value to it.

+
var MyOtherStore = require('../MyOtherStore');
+MyOtherStore.getState.mockReturnValue({
+  '123': {
+    id: '123',
+    text: 'foo'
+  },
+  '456': {
+    id: '456',
+    text: 'bar'
+  }
+});
+
+

Now we have a collection of objects that will come back from MyOtherStore whenever we call MyOtherStore.getState() in our tests. Any application state can be simulated with a combination of these custom return values and the previously shown technique of working with the store's registered callback.

+ +

A brief example of this technique is up on GitHub within the Flux Chat example's UnreadThreadStore-test.js.

+ +

For more information about the mock property of mocked methods or Jest's ability to provide custom mock values, see Jest's documentation on mock functions.

+

Moving Logic from React to Stores #

+

What often starts as a little piece of seemingly benign logic in our React components often presents a problem while creating unit tests. We want to be able to write tests that read like a specification for our application's behavior, and when application logic slips into our view layer, this becomes more difficult.

+ +

For example, when a user has marked each of their to-do items as complete, the TodoMVC specification dictates that we should also change the status of the "Mark all as complete" checkbox automatically. To create that logic, we might be tempted to write code like this in our MainSection's render() method:

+
var allTodos = this.props.allTodos;
+var allChecked = true;
+for (var id in allTodos) {
+  if (!allTodos[id].complete) {
+    allChecked = false;
+    break;
+  }
+}
+...
+
+return (
+  <section id="main">
+  <input
+    id="toggle-all"
+    type="checkbox"
+    checked={allChecked ? 'checked' : ''}
+  />
+  ...
+  </section>
+);
+
+

While this seems like an easy, normal thing to do, this is an example of application logic slipping into the views, and it can't be described in our spec-style TodoStore test. Let's take that logic and move it to the store. First, we'll create a public method on the store that will encapsulate that logic:

+
areAllComplete: function() {
+  for (var id in _todos) {
+    if (!_todos[id].complete) {
+      return false;
+    }
+  }
+  return true;
+},
+
+

Now we have the application logic where it belongs, and we can write the following test:

+
it('determines whether all to-do items are complete', function() {
+  var i = 0;
+  for (; i < 3; i++) {
+    callback(mockTodoCreate);
+  }
+  expect(TodoStore.areAllComplete()).toBe(false);
+
+  var all = TodoStore.getAll();
+  for (key in all) {
+    callback({
+      source: 'VIEW_ACTION',
+      action: {
+        actionType: TodoConstants.TODO_COMPLETE,
+        id: key
+      }
+    });
+  }
+  expect(TodoStore.areAllComplete()).toBe(true);
+
+  callback({
+    source: 'VIEW_ACTION',
+    action: {
+      actionType: TodoConstants.TODO_UNDO_COMPLETE,
+      id: key
+    }
+  });
+  expect(TodoStore.areAllComplete()).toBe(false);
+});
+
+

Finally, we revise our view layer. We'll call for that data in the controller-view, TodoApp.js, and pass it down to the MainSection component.

+
function getTodoState() {
+  return {
+    allTodos: TodoStore.getAll(),
+    areAllComplete: TodoStore.areAllComplete()
+  };
+}
+
+var TodoApp = React.createClass({
+...
+
+  /**
+   * @return {object}
+   */
+  render: function() {
+    return (
+      ...
+      <MainSection
+        allTodos={this.state.allTodos}
+        areAllComplete={this.state.areAllComplete}
+      />
+      ...
+    );
+  },
+
+  /**
+   * Event handler for 'change' events coming from the TodoStore
+   */
+  _onChange: function() {
+    this.setState(getTodoState());
+  }
+
+});
+
+

And then we'll utilize that property for the rendering of the checkbox.

+
render: function() {
+  ...
+
+  return (
+    <section id="main">
+    <input
+      id="toggle-all"
+      type="checkbox"
+      checked={this.props.areAllComplete ? 'checked' : ''}
+    />
+    ...
+    </section>
+  );
+},
+
+

To learn how to test React components themselves, check out the Jest tutorial for React and the ReactTestUtils documenation.

+

Further Reading #

+ + +
+
+

React v0.11.2

September 16, 2014 by Paul O’Shannessy

@@ -339,40 +611,6 @@

Random Tweets -

Flux: Actions and the Dispatcher

-

July 30, 2014 by Bill Fisher

-
-
-

Flux is the application architecture Facebook uses to build JavaScript applications. It's based on a unidirectional data flow. We've built everything from small widgets to huge applications with Flux, and it's handled everything we've thrown at it. Because we've found it to be a great way to structure our code, we're excited to share it with the open source community. Jing Chen presented Flux at the F8 conference, and since that time we've seen a lot of interest in it. We've also published an overview of Flux and a TodoMVC example, with an accompanying tutorial.

- -

Flux is more of a pattern than a full-blown framework, and you can start using it without a lot of new code beyond React. Up until recently, however, we haven't released one crucial piece of our Flux software: the dispatcher. But along with the creation of the new Flux code repository and Flux website, we've now open sourced the same dispatcher we use in our production applications.

-

Where the Dispatcher Fits in the Flux Data Flow #

-

The dispatcher is a singleton, and operates as the central hub of data flow in a Flux application. It is essentially a registry of callbacks, and can invoke these callbacks in order. Each store registers a callback with the dispatcher. When new data comes into the dispatcher, it then uses these callbacks to propagate that data to all of the stores. The process of invoking the callbacks is initiated through the dispatch() method, which takes a data payload object as its sole argument.

-

Actions and ActionCreators #

-

When new data enters the system, whether through a person interacting with the application or through a web api call, that data is packaged into an action — an object literal containing the new fields of data and a specific action type. We often create a library of helper methods called ActionCreators that not only create the action object, but also pass the action to the dispatcher.

- -

Different actions are identified by a type attribute. When all of the stores receive the action, they typically use this attribute to determine if and how they should respond to it. In a Flux application, both stores and views control themselves; they are not acted upon by external objects. Actions flow into the stores through the callbacks they define and register, not through setter methods.

- -

Letting the stores update themselves eliminates many entanglements typically found in MVC applications, where cascading updates between models can lead to unstable state and make accurate testing very difficult. The objects within a Flux application are highly decoupled, and adhere very strongly to the Law of Demeter, the principle that each object within a system should know as little as possible about the other objects in the system. This results in software that is more maintainable, adaptable, testable, and easier for new engineering team members to understand.

- -

-

Why We Need a Dispatcher #

-

As an application grows, dependencies across different stores are a near certainty. Store A will inevitably need Store B to update itself first, so that Store A can know how to update itself. We need the dispatcher to be able to invoke the callback for Store B, and finish that callback, before moving forward with Store A. To declaratively assert this dependency, a store needs to be able to say to the dispatcher, "I need to wait for Store B to finish processing this action." The dispatcher provides this functionality through its waitFor() method.

- -

The dispatch() method provides a simple, synchronous iteration through the callbacks, invoking each in turn. When waitFor() is encountered within one of the callbacks, execution of that callback stops and waitFor() provides us with a new iteration cycle over the dependencies. After the entire set of dependencies have been fulfilled, the original callback then continues to execute.

- -

Further, the waitFor() method may be used in different ways for different actions, within the same store's callback. In one case, Store A might need to wait for Store B. But in another case, it might need to wait for Store C. Using waitFor() within the code block that is specific to an action allows us to have fine-grained control of these dependencies.

- -

Problems arise, however, if we have circular dependencies. That is, if Store A needs to wait for Store B, and Store B needs to wait for Store A, we could wind up in an endless loop. The dispatcher now available in the Flux repo protects against this by throwing an informative error to alert the developer that this problem has occurred. The developer can then create a third store and resolve the circular dependency.

-

Example Chat App #

-

Along with the same dispatcher that Facebook uses in its production applications, we've also published a new example chat app, slightly more complicated than the simplistic TodoMVC, so that engineers can better understand how Flux solves problems like dependencies between stores and calls to a web API.

- -

We're hopeful that the new Flux repository will grow with time to include additional tools, boilerplate code and further examples. And we hope that Flux will prove as useful to you as it has to us. Enjoy!

- -
-

- @@ -90,6 +90,46 @@

Recent posts

+
+

New in React v0.4: Autobind by Default

+

July 2, 2013 by Paul O'Shannessy

+
+
+

React v0.4 is very close to completion. As we finish it off, we'd like to share with you some of the major changes we've made since v0.3. This is the first of several posts we'll be making over the next week.

+

What is React.autoBind? #

+

If you take a look at most of our current examples, you'll see us using React.autoBind for event handlers. This is used in place of Function.prototype.bind. Remember that in JS, function calls are late-bound. That means that if you simply pass a function around, the this used inside won't necessarily be the this you expect. Function.prototype.bind creates a new, properly bound, function so that when called, this is exactly what you expect it to be.

+ +

Before we launched React, we would write this:

+
React.createClass({
+  onClick: function(event) {/* do something with this */},
+  render: function() {
+    return <button onClick={this.onClick.bind(this)} />;
+  }
+});
+
+

We wrote React.autoBind as a way to cache the function creation and save on memory usage. Since render can get called multiple times, if you used this.onClick.bind(this) you would actually create a new function on each pass. With React v0.3 you were able to write this instead:

+
React.createClass({
+  onClick: React.autoBind(function(event) {/* do something with this */}),
+  render: function() {
+    return <button onClick={this.onClick} />;
+  }
+});
+

What's Changing in v0.4? #

+

After using React.autoBind for a few weeks, we realized that there were very few times that we didn't want that behavior. So we made it the default! Now all methods defined within React.createClass will already be bound to the correct instance.

+ +

Starting with v0.4 you can just write this:

+
React.createClass({
+  onClick: function(event) {/* do something with this */},
+  render: function() {
+    return <button onClick={this.onClick} />;
+  }
+});
+
+

For v0.4 we will simply be making React.autoBind a no-op — it will just return the function you pass to it. Most likely you won't have to change your code to account for this change, though we encourage you to update. We'll publish a migration guide documenting this and other changes that come along with React v0.4.

+ +
+
+

Community Round-up #3

June 27, 2013 by Vjeux

@@ -322,96 +362,6 @@

Origins of React -

Why did we build React?

-

June 5, 2013 by Pete Hunt

-
-
-

There are a lot of JavaScript MVC frameworks out there. Why did we build React -and why would you want to use it?

-

React isn't an MVC framework. #

-

React is a library for building composable user interfaces. It encourages -the creation of reusable UI components which present data that changes over -time.

-

React doesn't use templates. #

-

Traditionally, web application UIs are built using templates or HTML directives. -These templates dictate the full set of abstractions that you are allowed to use -to build your UI.

- -

React approaches building user interfaces differently by breaking them into -components. This means React uses a real, full featured programming language -to render views, which we see as an advantage over templates for a few reasons:

- -
    -
  • JavaScript is a flexible, powerful programming language with the ability -to build abstractions. This is incredibly important in large applications.
  • -
  • By unifying your markup with its corresponding view logic, React can actually -make views easier to extend and maintain.
  • -
  • By baking an understanding of markup and content into JavaScript, there's -no manual string concatenation and therefore less surface area for XSS -vulnerabilities.
  • -
- -

We've also created JSX, an optional syntax -extension, in case you prefer the readability of HTML to raw JavaScript.

-

Reactive updates are dead simple. #

-

React really shines when your data changes over time.

- -

In a traditional JavaScript application, you need to look at what data changed -and imperatively make changes to the DOM to keep it up-to-date. Even AngularJS, -which provides a declarative interface via directives and data binding requires -a linking function to manually update DOM nodes.

- -

React takes a different approach.

- -

When your component is first initialized, the render method is called, -generating a lightweight representation of your view. From that representation, -a string of markup is produced, and injected into the document. When your data -changes, the render method is called again. In order to perform updates as -efficiently as possible, we diff the return value from the previous call to -render with the new one, and generate a minimal set of changes to be applied -to the DOM.

- -
-

The data returned from render is neither a string nor a DOM node -- it's a -lightweight description of what the DOM should look like.

-
- -

We call this process reconciliation. Check out -this jsFiddle to see an example of -reconciliation in action.

- -

Because this re-render is so fast (around 1ms for TodoMVC), the developer -doesn't need to explicitly specify data bindings. We've found this approach -makes it easier to build apps.

-

HTML is just the beginning. #

-

Because React has its own lightweight representation of the document, we can do -some pretty cool things with it:

- -
    -
  • Facebook has dynamic charts that render to <canvas> instead of HTML.
  • -
  • Instagram is a "single page" web app built entirely with React and -Backbone.Router. Designers regularly contribute React code with JSX.
  • -
  • We've built internal prototypes that run React apps in a web worker and use -React to drive native iOS views via an Objective-C bridge.
  • -
  • You can run React -on the server -for SEO, performance, code sharing and overall flexibility.
  • -
  • Events behave in a consistent, standards-compliant way in all browsers -(including IE8) and automatically use -event delegation.
  • -
- -

Head on over to facebook.github.io/react to check out what we have -built. Our documentation is geared towards building apps with the framework, -but if you are interested in the nuts and bolts -get in touch with us!

- -

Thanks for reading!

- -
-

- @@ -90,6 +90,96 @@

Recent posts

+
+

Why did we build React?

+

June 5, 2013 by Pete Hunt

+
+
+

There are a lot of JavaScript MVC frameworks out there. Why did we build React +and why would you want to use it?

+

React isn't an MVC framework. #

+

React is a library for building composable user interfaces. It encourages +the creation of reusable UI components which present data that changes over +time.

+

React doesn't use templates. #

+

Traditionally, web application UIs are built using templates or HTML directives. +These templates dictate the full set of abstractions that you are allowed to use +to build your UI.

+ +

React approaches building user interfaces differently by breaking them into +components. This means React uses a real, full featured programming language +to render views, which we see as an advantage over templates for a few reasons:

+ +
    +
  • JavaScript is a flexible, powerful programming language with the ability +to build abstractions. This is incredibly important in large applications.
  • +
  • By unifying your markup with its corresponding view logic, React can actually +make views easier to extend and maintain.
  • +
  • By baking an understanding of markup and content into JavaScript, there's +no manual string concatenation and therefore less surface area for XSS +vulnerabilities.
  • +
+ +

We've also created JSX, an optional syntax +extension, in case you prefer the readability of HTML to raw JavaScript.

+

Reactive updates are dead simple. #

+

React really shines when your data changes over time.

+ +

In a traditional JavaScript application, you need to look at what data changed +and imperatively make changes to the DOM to keep it up-to-date. Even AngularJS, +which provides a declarative interface via directives and data binding requires +a linking function to manually update DOM nodes.

+ +

React takes a different approach.

+ +

When your component is first initialized, the render method is called, +generating a lightweight representation of your view. From that representation, +a string of markup is produced, and injected into the document. When your data +changes, the render method is called again. In order to perform updates as +efficiently as possible, we diff the return value from the previous call to +render with the new one, and generate a minimal set of changes to be applied +to the DOM.

+ +
+

The data returned from render is neither a string nor a DOM node -- it's a +lightweight description of what the DOM should look like.

+
+ +

We call this process reconciliation. Check out +this jsFiddle to see an example of +reconciliation in action.

+ +

Because this re-render is so fast (around 1ms for TodoMVC), the developer +doesn't need to explicitly specify data bindings. We've found this approach +makes it easier to build apps.

+

HTML is just the beginning. #

+

Because React has its own lightweight representation of the document, we can do +some pretty cool things with it:

+ +
    +
  • Facebook has dynamic charts that render to <canvas> instead of HTML.
  • +
  • Instagram is a "single page" web app built entirely with React and +Backbone.Router. Designers regularly contribute React code with JSX.
  • +
  • We've built internal prototypes that run React apps in a web worker and use +React to drive native iOS views via an Objective-C bridge.
  • +
  • You can run React +on the server +for SEO, performance, code sharing and overall flexibility.
  • +
  • Events behave in a consistent, standards-compliant way in all browsers +(including IE8) and automatically use +event delegation.
  • +
+ +

Head on over to facebook.github.io/react to check out what we have +built. Our documentation is geared towards building apps with the framework, +but if you are interested in the nuts and bolts +get in touch with us!

+ +

Thanks for reading!

+ +
+
+

JSFiddle Integration

June 2, 2013 by Christopher Chedeau

diff --git a/blog/page2/index.html b/blog/page2/index.html index 7c419d81cf..fcc560ffb0 100644 --- a/blog/page2/index.html +++ b/blog/page2/index.html @@ -63,6 +63,8 @@

Recent posts

@@ -90,6 +90,40 @@

Recent posts

+
+

Flux: Actions and the Dispatcher

+

July 30, 2014 by Bill Fisher

+
+
+

Flux is the application architecture Facebook uses to build JavaScript applications. It's based on a unidirectional data flow. We've built everything from small widgets to huge applications with Flux, and it's handled everything we've thrown at it. Because we've found it to be a great way to structure our code, we're excited to share it with the open source community. Jing Chen presented Flux at the F8 conference, and since that time we've seen a lot of interest in it. We've also published an overview of Flux and a TodoMVC example, with an accompanying tutorial.

+ +

Flux is more of a pattern than a full-blown framework, and you can start using it without a lot of new code beyond React. Up until recently, however, we haven't released one crucial piece of our Flux software: the dispatcher. But along with the creation of the new Flux code repository and Flux website, we've now open sourced the same dispatcher we use in our production applications.

+

Where the Dispatcher Fits in the Flux Data Flow #

+

The dispatcher is a singleton, and operates as the central hub of data flow in a Flux application. It is essentially a registry of callbacks, and can invoke these callbacks in order. Each store registers a callback with the dispatcher. When new data comes into the dispatcher, it then uses these callbacks to propagate that data to all of the stores. The process of invoking the callbacks is initiated through the dispatch() method, which takes a data payload object as its sole argument.

+

Actions and ActionCreators #

+

When new data enters the system, whether through a person interacting with the application or through a web api call, that data is packaged into an action — an object literal containing the new fields of data and a specific action type. We often create a library of helper methods called ActionCreators that not only create the action object, but also pass the action to the dispatcher.

+ +

Different actions are identified by a type attribute. When all of the stores receive the action, they typically use this attribute to determine if and how they should respond to it. In a Flux application, both stores and views control themselves; they are not acted upon by external objects. Actions flow into the stores through the callbacks they define and register, not through setter methods.

+ +

Letting the stores update themselves eliminates many entanglements typically found in MVC applications, where cascading updates between models can lead to unstable state and make accurate testing very difficult. The objects within a Flux application are highly decoupled, and adhere very strongly to the Law of Demeter, the principle that each object within a system should know as little as possible about the other objects in the system. This results in software that is more maintainable, adaptable, testable, and easier for new engineering team members to understand.

+ +

+

Why We Need a Dispatcher #

+

As an application grows, dependencies across different stores are a near certainty. Store A will inevitably need Store B to update itself first, so that Store A can know how to update itself. We need the dispatcher to be able to invoke the callback for Store B, and finish that callback, before moving forward with Store A. To declaratively assert this dependency, a store needs to be able to say to the dispatcher, "I need to wait for Store B to finish processing this action." The dispatcher provides this functionality through its waitFor() method.

+ +

The dispatch() method provides a simple, synchronous iteration through the callbacks, invoking each in turn. When waitFor() is encountered within one of the callbacks, execution of that callback stops and waitFor() provides us with a new iteration cycle over the dependencies. After the entire set of dependencies have been fulfilled, the original callback then continues to execute.

+ +

Further, the waitFor() method may be used in different ways for different actions, within the same store's callback. In one case, Store A might need to wait for Store B. But in another case, it might need to wait for Store C. Using waitFor() within the code block that is specific to an action allows us to have fine-grained control of these dependencies.

+ +

Problems arise, however, if we have circular dependencies. That is, if Store A needs to wait for Store B, and Store B needs to wait for Store A, we could wind up in an endless loop. The dispatcher now available in the Flux repo protects against this by throwing an informative error to alert the developer that this problem has occurred. The developer can then create a third store and resolve the circular dependency.

+

Example Chat App #

+

Along with the same dispatcher that Facebook uses in its production applications, we've also published a new example chat app, slightly more complicated than the simplistic TodoMVC, so that engineers can better understand how Flux solves problems like dependencies between stores and calls to a web API.

+ +

We're hopeful that the new Flux repository will grow with time to include additional tools, boilerplate code and further examples. And we hope that Flux will prove as useful to you as it has to us. Enjoy!

+ +
+
+

Community Round-up #20

July 28, 2014 by Lou Husson

@@ -509,57 +543,6 @@

React Tools Module

-
-

Community Round-up #19

-

June 27, 2014 by Cheng Lou

-
-
-

React Meetups! #

-

Ever wanted to find developers who also share the same interest in React than you? Recently, there has been a React Meetup in San Francisco (courtesy of Telmate), and one in London (courtesy of Stuart Harris, Cain Ullah and Zoe Merchant). These two events have been big successes; a second one in London is already planned.

- -

If you don't live near San Francisco or London, why not start one in your community?

-

Complementary Tools #

-

In case you haven't seen it, we've consolidated the tooling solution around React on this wiki page. Some of the notable recent entries include:

- - - -

These are some of the links that often pop up on the #reactjs IRC channel. If you made something that you think deserves to be shown on the wiki, feel free to add it!

-

React in Interesting Places #

-

The core concepts React themselves is something very valuable that the community is exploring and pushing further. A year ago, we wouldn't have imagined something like Bruce Hauman's Flappy Bird ClojureScript port, whose interactive programming has been made possible through React:

- - - -

And don't forget Pete Hunt's Wolfenstein 3D rendering engine in React (source code). While it's nearly a year old, it's still a nice demo.

- -

- -

Give us a shoutout on IRC or React Google Groups if you've used React in some Interesting places.

-

Even More People Using React #

Prismatic #

-

Prismatic recently shrank their codebase fivefold with the help of React and its popular ClojureScript wrapper, Om. They detailed their very positive experience here.

- -
-

Finally, the state is normalized: each piece of information is represented in a single place. Since React ensures consistency between the DOM and the application data, the programmer can focus on ensuring that the state properly stays up to date in response to user input. If the application state is normalized, then this consistency is guaranteed by definition, completely avoiding the possibility of an entire class of common bugs.

-
-

Adobe Brackets #

-

Kevin Dangoor works on Brackets, the open-source code editor. After writing his first impression on React, he followed up with another insightful article on how to gradually make the code transition, how to preserve the editor's good parts, and how to tune Brackets' tooling around JSX.

- -
-

We don’t need to switch to React everywhere, all at once. It’s not a framework that imposes anything on the application structure. [...] Easy, iterative adoption is definitely something in React’s favor for us.

-
-

Storehouse #

-

Storehouse (Apple Design Award 2014)'s web presence is build with React. Here's an example story. Congratulations on the award!

-

Vim Awesome #

-

Vim Awesome, an open-source Vim plugins directory built on React, was just launched. Be sure to check out the source code if you're curious to see an example of how to build a small single-page React app.

-

Random Tweets #

- - -
-
- @@ -90,6 +90,57 @@

Recent posts

+
+

Community Round-up #19

+

June 27, 2014 by Cheng Lou

+
+
+

React Meetups! #

+

Ever wanted to find developers who also share the same interest in React than you? Recently, there has been a React Meetup in San Francisco (courtesy of Telmate), and one in London (courtesy of Stuart Harris, Cain Ullah and Zoe Merchant). These two events have been big successes; a second one in London is already planned.

+ +

If you don't live near San Francisco or London, why not start one in your community?

+

Complementary Tools #

+

In case you haven't seen it, we've consolidated the tooling solution around React on this wiki page. Some of the notable recent entries include:

+ + + +

These are some of the links that often pop up on the #reactjs IRC channel. If you made something that you think deserves to be shown on the wiki, feel free to add it!

+

React in Interesting Places #

+

The core concepts React themselves is something very valuable that the community is exploring and pushing further. A year ago, we wouldn't have imagined something like Bruce Hauman's Flappy Bird ClojureScript port, whose interactive programming has been made possible through React:

+ + + +

And don't forget Pete Hunt's Wolfenstein 3D rendering engine in React (source code). While it's nearly a year old, it's still a nice demo.

+ +

+ +

Give us a shoutout on IRC or React Google Groups if you've used React in some Interesting places.

+

Even More People Using React #

Prismatic #

+

Prismatic recently shrank their codebase fivefold with the help of React and its popular ClojureScript wrapper, Om. They detailed their very positive experience here.

+ +
+

Finally, the state is normalized: each piece of information is represented in a single place. Since React ensures consistency between the DOM and the application data, the programmer can focus on ensuring that the state properly stays up to date in response to user input. If the application state is normalized, then this consistency is guaranteed by definition, completely avoiding the possibility of an entire class of common bugs.

+
+

Adobe Brackets #

+

Kevin Dangoor works on Brackets, the open-source code editor. After writing his first impression on React, he followed up with another insightful article on how to gradually make the code transition, how to preserve the editor's good parts, and how to tune Brackets' tooling around JSX.

+ +
+

We don’t need to switch to React everywhere, all at once. It’s not a framework that imposes anything on the application structure. [...] Easy, iterative adoption is definitely something in React’s favor for us.

+
+

Storehouse #

+

Storehouse (Apple Design Award 2014)'s web presence is build with React. Here's an example story. Congratulations on the award!

+

Vim Awesome #

+

Vim Awesome, an open-source Vim plugins directory built on React, was just launched. Be sure to check out the source code if you're curious to see an example of how to build a small single-page React app.

+

Random Tweets #

+ + +
+
+

One Year of Open-Source React

May 29, 2014 by Cheng Lou

@@ -206,80 +257,6 @@

Miscellaneous -

React v0.10

-

March 21, 2014 by Paul O’Shannessy

-
-
-

Hot on the heels of the release candidate earlier this week, we're ready to call v0.10 done. The only major issue we discovered had to do with the react-tools package, which has been updated. We've copied over the changelog from the RC with some small clarifying changes.

- -

The release is available for download from the CDN:

- - - -

We've also published version 0.10.0 of the react and react-tools packages on npm and the react package on bower.

- -

Please try these builds out and file an issue on GitHub if you see anything awry.

-

Clone On Mount #

-

The main purpose of this release is to provide a smooth upgrade path as we evolve some of the implementation of core. In v0.9 we started warning in cases where you called methods on unmounted components. This is part of an effort to enforce the idea that the return value of a component (React.DOM.div(), MyComponent()) is in fact not a reference to the component instance React uses in the virtual DOM. The return value is instead a light-weight object that React knows how to use. Since the return value currently is a reference to the same object React uses internally, we need to make this transition in stages as many people have come to depend on this implementation detail.

- -

In 0.10, we’re adding more warnings to catch a similar set of patterns. When a component is mounted we clone it and use that object for our internal representation. This allows us to capture calls you think you’re making to a mounted component. We’ll forward them on to the right object, but also warn you that this is breaking. See “Access to the Mounted Instance” on this page. Most of the time you can solve your pattern by using refs.

- -

Storing a reference to your top level component is a pattern touched upon on that page, but another examples that demonstrates what we see a lot of:

-
// This is a common pattern. However instance here really refers to a
-// "descriptor", not necessarily the mounted instance.
-var instance = <MyComponent/>;
-React.renderComponent(instance);
-// ...
-instance.setProps(...);
-
-// The change here is very simple. The return value of renderComponent will be
-// the mounted instance.
-var instance = React.renderComponent(<MyComponent/>)
-// ...
-instance.setProps(...);
-
-

These warnings and method forwarding are only enabled in the development build. The production builds continue to work as they did in v0.9. We strongly encourage you to use the development builds to catch these warnings and fix the call sites.

- -

The plan for v0.11 is that we will go fully to "descriptors". Method calls on the return value of MyComponent() will fail hard.

-

Changelog #

React Core #

New Features #

-
    -
  • Added warnings to help migrate towards descriptors
  • -
  • Made it possible to server render without React-related markup (data-reactid, data-react-checksum). This DOM will not be mountable by React. Read the docs for React.renderComponentToStaticMarkup
  • -
  • Added support for more attributes: - -
      -
    • srcSet for <img> to specify images at different pixel ratios
    • -
    • textAnchor for SVG
    • -
  • -
-

Bug Fixes #

-
    -
  • Ensure all void elements don’t insert a closing tag into the markup.
  • -
  • Ensure className={false} behaves consistently
  • -
  • Ensure this.refs is defined, even if no refs are specified.
  • -
-

Addons #

- -

react-tools #

-
    -
  • Added an option argument to transform function. The only option supported is harmony, which behaves the same as jsx --harmony on the command line. This uses the ES6 transforms from jstransform.
  • -
- -
-

- @@ -90,6 +90,80 @@

Recent posts

+
+

React v0.10

+

March 21, 2014 by Paul O’Shannessy

+
+
+

Hot on the heels of the release candidate earlier this week, we're ready to call v0.10 done. The only major issue we discovered had to do with the react-tools package, which has been updated. We've copied over the changelog from the RC with some small clarifying changes.

+ +

The release is available for download from the CDN:

+ + + +

We've also published version 0.10.0 of the react and react-tools packages on npm and the react package on bower.

+ +

Please try these builds out and file an issue on GitHub if you see anything awry.

+

Clone On Mount #

+

The main purpose of this release is to provide a smooth upgrade path as we evolve some of the implementation of core. In v0.9 we started warning in cases where you called methods on unmounted components. This is part of an effort to enforce the idea that the return value of a component (React.DOM.div(), MyComponent()) is in fact not a reference to the component instance React uses in the virtual DOM. The return value is instead a light-weight object that React knows how to use. Since the return value currently is a reference to the same object React uses internally, we need to make this transition in stages as many people have come to depend on this implementation detail.

+ +

In 0.10, we’re adding more warnings to catch a similar set of patterns. When a component is mounted we clone it and use that object for our internal representation. This allows us to capture calls you think you’re making to a mounted component. We’ll forward them on to the right object, but also warn you that this is breaking. See “Access to the Mounted Instance” on this page. Most of the time you can solve your pattern by using refs.

+ +

Storing a reference to your top level component is a pattern touched upon on that page, but another examples that demonstrates what we see a lot of:

+
// This is a common pattern. However instance here really refers to a
+// "descriptor", not necessarily the mounted instance.
+var instance = <MyComponent/>;
+React.renderComponent(instance);
+// ...
+instance.setProps(...);
+
+// The change here is very simple. The return value of renderComponent will be
+// the mounted instance.
+var instance = React.renderComponent(<MyComponent/>)
+// ...
+instance.setProps(...);
+
+

These warnings and method forwarding are only enabled in the development build. The production builds continue to work as they did in v0.9. We strongly encourage you to use the development builds to catch these warnings and fix the call sites.

+ +

The plan for v0.11 is that we will go fully to "descriptors". Method calls on the return value of MyComponent() will fail hard.

+

Changelog #

React Core #

New Features #

+
    +
  • Added warnings to help migrate towards descriptors
  • +
  • Made it possible to server render without React-related markup (data-reactid, data-react-checksum). This DOM will not be mountable by React. Read the docs for React.renderComponentToStaticMarkup
  • +
  • Added support for more attributes: + +
      +
    • srcSet for <img> to specify images at different pixel ratios
    • +
    • textAnchor for SVG
    • +
  • +
+

Bug Fixes #

+
    +
  • Ensure all void elements don’t insert a closing tag into the markup.
  • +
  • Ensure className={false} behaves consistently
  • +
  • Ensure this.refs is defined, even if no refs are specified.
  • +
+

Addons #

+ +

react-tools #

+
    +
  • Added an option argument to transform function. The only option supported is harmony, which behaves the same as jsx --harmony on the command line. This uses the ES6 transforms from jstransform.
  • +
+ +
+
+

React v0.10 RC

March 19, 2014 by Paul O’Shannessy

@@ -437,132 +511,6 @@

JSX Compil

-
-

React v0.9 RC

-

February 16, 2014 by Ben Alpert

-
-
-

We're almost ready to release React v0.9! We're posting a release candidate so that you can test your apps on it; we'd much prefer to find show-stopping bugs now rather than after we release.

- -

The release candidate is available for download from the CDN:

- - - -

We've also published version 0.9.0-rc1 of the react and react-tools packages on npm and the react package on bower.

- -

Please try these builds out and file an issue on GitHub if you see anything awry.

-

Upgrade Notes #

-

In addition to the changes to React core listed below, we've made a small change to the way JSX interprets whitespace to make things more consistent. With this release, space between two components on the same line will be preserved, while a newline separating a text node from a tag will be eliminated in the output. Consider the code:

-
<div>
-  Monkeys:
-  {listOfMonkeys} {submitButton}
-</div>
-
-

In v0.8 and below, it was transformed to the following:

-
React.DOM.div(null,
-  " Monkeys: ",
-  listOfMonkeys, submitButton
-)
-
-

In v0.9, it will be transformed to this JS instead:

-
React.DOM.div(null,
-  "Monkeys:",
-  listOfMonkeys, " ", submitButton
-)
-
-

We believe this new behavior is more helpful and elimates cases where unwanted whitespace was previously added.

- -

In cases where you want to preserve the space adjacent to a newline, you can write a JS string like {"Monkeys: "} in your JSX source. We've included a script to do an automated codemod of your JSX source tree that preserves the old whitespace behavior by adding and removing spaces appropriately. You can install jsx_whitespace_transformer from npm and run it over your source tree to modify files in place. The transformed JSX files will preserve your code's existing whitespace behavior.

-

Changelog #

React Core #

Breaking Changes #

-
    -
  • The lifecycle methods componentDidMount and componentDidUpdate no longer receive the root node as a parameter; use this.getDOMNode() instead
  • -
  • Whenever a prop is equal to undefined, the default value returned by getDefaultProps will now be used instead
  • -
  • React.unmountAndReleaseReactRootNode was previously deprecated and has now been removed
  • -
  • React.renderComponentToString is now synchronous and returns the generated HTML string
  • -
  • Full-page rendering (that is, rendering the <html> tag using React) is now supported only when starting with server-rendered markup
  • -
  • On mouse wheel events, deltaY is no longer negated
  • -
  • When prop types validation fails, a warning is logged instead of an error thrown (with the production build of React, the type checks are now skipped for performance)
  • -
  • On input, select, and textarea elements, .getValue() is no longer supported; use .getDOMNode().value instead
  • -
  • this.context on components is now reserved for internal use by React
  • -
-

New Features #

-
    -
  • React now never rethrows errors, so stack traces are more accurate and Chrome's purple break-on-error stop sign now works properly
  • -
  • Added a new tool for profiling React components and identifying places where defining shouldComponentUpdate can give performance improvements
  • -
  • Added support for SVG tags defs, linearGradient, polygon, radialGradient, stop
  • -
  • Added support for more attributes: - -
      -
    • noValidate and formNoValidate for forms
    • -
    • property for Open Graph <meta> tags
    • -
    • sandbox, seamless, and srcDoc for <iframe> tags
    • -
    • scope for screen readers
    • -
    • span for <colgroup> tags
    • -
  • -
  • Added support for defining propTypes in mixins
  • -
  • Added any, arrayOf, component, oneOfType, renderable, shape to React.PropTypes
  • -
  • Added support for statics on component spec for static component methods
  • -
  • On all events, .currentTarget is now properly set
  • -
  • On keyboard events, .key is now polyfilled in all browsers for special (non-printable) keys
  • -
  • On clipboard events, .clipboardData is now polyfilled in IE
  • -
  • On drag events, .dataTransfer is now present
  • -
  • Added support for onMouseOver and onMouseOut in addition to the existing onMouseEnter and onMouseLeave events
  • -
  • Added support for onLoad and onError on <img> elements
  • -
  • Added support for onReset on <form> elements
  • -
  • The autoFocus attribute is now polyfilled consistently on input, select, and textarea
  • -
-

Bug Fixes #

-
    -
  • React no longer adds an __owner__ property to each component's props object; passed-in props are now never mutated
  • -
  • When nesting top-level components (e.g., calling React.renderComponent within componentDidMount), events now properly bubble to the parent component
  • -
  • Fixed a case where nesting top-level components would throw an error when updating
  • -
  • Passing an invalid or misspelled propTypes type now throws an error
  • -
  • On mouse enter/leave events, .target, .relatedTarget, and .type are now set properly
  • -
  • On composition events, .data is now properly normalized in IE9 and IE10
  • -
  • CSS property values no longer have px appended for the unitless properties columnCount, flex, flexGrow, flexShrink, lineClamp, order, widows
  • -
  • Fixed a memory leak when unmounting children with a componentWillUnmount handler
  • -
  • Fixed a memory leak when renderComponentToString would store event handlers
  • -
  • Fixed an error that could be thrown when removing form elements during a click handler
  • -
  • key values containing . are now supported
  • -
  • Shortened data-reactid values for performance
  • -
  • Components now always remount when the key property changes
  • -
  • Event handlers are attached to document only when necessary, improving performance in some cases
  • -
  • Events no longer use .returnValue in modern browsers, eliminating a warning in Chrome
  • -
  • scrollLeft and scrollTop are no longer accessed on document.body, eliminating a warning in Chrome
  • -
  • General performance fixes, memory optimizations, improvements to warnings and error messages
  • -
-

React with Addons #

-
    -
  • React.addons.TransitionGroup was renamed to React.addons.CSSTransitionGroup
  • -
  • React.addons.TransitionGroup was added as a more general animation wrapper
  • -
  • React.addons.cloneWithProps was added for cloning components and modifying their props
  • -
  • Bug fix for adding back nodes during an exit transition for CSSTransitionGroup
  • -
  • Bug fix for changing transitionLeave in CSSTransitionGroup
  • -
  • Performance optimizations for CSSTransitionGroup
  • -
  • On checkbox <input> elements, checkedLink is now supported for two-way binding
  • -
-

JSX Compiler and react-tools Package #

-
    -
  • Whitespace normalization has changed; now space between two tags on the same line will be preserved, while newlines between two tags will be removed
  • -
  • The react-tools npm package no longer includes the React core libraries; use the react package instead.
  • -
  • displayName is now added in more cases, improving error messages and names in the React Dev Tools
  • -
  • Fixed an issue where an invalid token error was thrown after a JSX closing tag
  • -
  • JSXTransformer now uses source maps automatically in modern browsers
  • -
  • JSXTransformer error messages now include the filename and problematic line contents when a file fails to parse
  • -
- -
-
- @@ -90,6 +90,132 @@

Recent posts

+
+

React v0.9 RC

+

February 16, 2014 by Ben Alpert

+
+
+

We're almost ready to release React v0.9! We're posting a release candidate so that you can test your apps on it; we'd much prefer to find show-stopping bugs now rather than after we release.

+ +

The release candidate is available for download from the CDN:

+ + + +

We've also published version 0.9.0-rc1 of the react and react-tools packages on npm and the react package on bower.

+ +

Please try these builds out and file an issue on GitHub if you see anything awry.

+

Upgrade Notes #

+

In addition to the changes to React core listed below, we've made a small change to the way JSX interprets whitespace to make things more consistent. With this release, space between two components on the same line will be preserved, while a newline separating a text node from a tag will be eliminated in the output. Consider the code:

+
<div>
+  Monkeys:
+  {listOfMonkeys} {submitButton}
+</div>
+
+

In v0.8 and below, it was transformed to the following:

+
React.DOM.div(null,
+  " Monkeys: ",
+  listOfMonkeys, submitButton
+)
+
+

In v0.9, it will be transformed to this JS instead:

+
React.DOM.div(null,
+  "Monkeys:",
+  listOfMonkeys, " ", submitButton
+)
+
+

We believe this new behavior is more helpful and elimates cases where unwanted whitespace was previously added.

+ +

In cases where you want to preserve the space adjacent to a newline, you can write a JS string like {"Monkeys: "} in your JSX source. We've included a script to do an automated codemod of your JSX source tree that preserves the old whitespace behavior by adding and removing spaces appropriately. You can install jsx_whitespace_transformer from npm and run it over your source tree to modify files in place. The transformed JSX files will preserve your code's existing whitespace behavior.

+

Changelog #

React Core #

Breaking Changes #

+
    +
  • The lifecycle methods componentDidMount and componentDidUpdate no longer receive the root node as a parameter; use this.getDOMNode() instead
  • +
  • Whenever a prop is equal to undefined, the default value returned by getDefaultProps will now be used instead
  • +
  • React.unmountAndReleaseReactRootNode was previously deprecated and has now been removed
  • +
  • React.renderComponentToString is now synchronous and returns the generated HTML string
  • +
  • Full-page rendering (that is, rendering the <html> tag using React) is now supported only when starting with server-rendered markup
  • +
  • On mouse wheel events, deltaY is no longer negated
  • +
  • When prop types validation fails, a warning is logged instead of an error thrown (with the production build of React, the type checks are now skipped for performance)
  • +
  • On input, select, and textarea elements, .getValue() is no longer supported; use .getDOMNode().value instead
  • +
  • this.context on components is now reserved for internal use by React
  • +
+

New Features #

+
    +
  • React now never rethrows errors, so stack traces are more accurate and Chrome's purple break-on-error stop sign now works properly
  • +
  • Added a new tool for profiling React components and identifying places where defining shouldComponentUpdate can give performance improvements
  • +
  • Added support for SVG tags defs, linearGradient, polygon, radialGradient, stop
  • +
  • Added support for more attributes: + +
      +
    • noValidate and formNoValidate for forms
    • +
    • property for Open Graph <meta> tags
    • +
    • sandbox, seamless, and srcDoc for <iframe> tags
    • +
    • scope for screen readers
    • +
    • span for <colgroup> tags
    • +
  • +
  • Added support for defining propTypes in mixins
  • +
  • Added any, arrayOf, component, oneOfType, renderable, shape to React.PropTypes
  • +
  • Added support for statics on component spec for static component methods
  • +
  • On all events, .currentTarget is now properly set
  • +
  • On keyboard events, .key is now polyfilled in all browsers for special (non-printable) keys
  • +
  • On clipboard events, .clipboardData is now polyfilled in IE
  • +
  • On drag events, .dataTransfer is now present
  • +
  • Added support for onMouseOver and onMouseOut in addition to the existing onMouseEnter and onMouseLeave events
  • +
  • Added support for onLoad and onError on <img> elements
  • +
  • Added support for onReset on <form> elements
  • +
  • The autoFocus attribute is now polyfilled consistently on input, select, and textarea
  • +
+

Bug Fixes #

+
    +
  • React no longer adds an __owner__ property to each component's props object; passed-in props are now never mutated
  • +
  • When nesting top-level components (e.g., calling React.renderComponent within componentDidMount), events now properly bubble to the parent component
  • +
  • Fixed a case where nesting top-level components would throw an error when updating
  • +
  • Passing an invalid or misspelled propTypes type now throws an error
  • +
  • On mouse enter/leave events, .target, .relatedTarget, and .type are now set properly
  • +
  • On composition events, .data is now properly normalized in IE9 and IE10
  • +
  • CSS property values no longer have px appended for the unitless properties columnCount, flex, flexGrow, flexShrink, lineClamp, order, widows
  • +
  • Fixed a memory leak when unmounting children with a componentWillUnmount handler
  • +
  • Fixed a memory leak when renderComponentToString would store event handlers
  • +
  • Fixed an error that could be thrown when removing form elements during a click handler
  • +
  • key values containing . are now supported
  • +
  • Shortened data-reactid values for performance
  • +
  • Components now always remount when the key property changes
  • +
  • Event handlers are attached to document only when necessary, improving performance in some cases
  • +
  • Events no longer use .returnValue in modern browsers, eliminating a warning in Chrome
  • +
  • scrollLeft and scrollTop are no longer accessed on document.body, eliminating a warning in Chrome
  • +
  • General performance fixes, memory optimizations, improvements to warnings and error messages
  • +
+

React with Addons #

+
    +
  • React.addons.TransitionGroup was renamed to React.addons.CSSTransitionGroup
  • +
  • React.addons.TransitionGroup was added as a more general animation wrapper
  • +
  • React.addons.cloneWithProps was added for cloning components and modifying their props
  • +
  • Bug fix for adding back nodes during an exit transition for CSSTransitionGroup
  • +
  • Bug fix for changing transitionLeave in CSSTransitionGroup
  • +
  • Performance optimizations for CSSTransitionGroup
  • +
  • On checkbox <input> elements, checkedLink is now supported for two-way binding
  • +
+

JSX Compiler and react-tools Package #

+
    +
  • Whitespace normalization has changed; now space between two tags on the same line will be preserved, while newlines between two tags will be removed
  • +
  • The react-tools npm package no longer includes the React core libraries; use the react package instead.
  • +
  • displayName is now added in more cases, improving error messages and names in the React Dev Tools
  • +
  • Fixed an issue where an invalid token error was thrown after a JSX closing tag
  • +
  • JSXTransformer now uses source maps automatically in modern browsers
  • +
  • JSXTransformer error messages now include the filename and problematic line contents when a file fails to parse
  • +
+ +
+
+

Community Round-up #16

February 15, 2014 by Jonas Gebhardt

@@ -364,103 +490,6 @@

React Chr

-
-

Community Round-up #13

-

December 30, 2013 by Vjeux

-
-
-

Happy holidays! This blog post is a little-late Christmas present for all the React users. Hopefully it will inspire you to write awesome web apps in 2014!

-

React Touch #

-

Pete Hunt wrote three demos showing that React can be used to run 60fps native-like experiences on mobile web. A frosted glass effect, an image gallery with 3d animations and an infinite scroll view.

- -
- -

Try out the demos!

-

Introduction to React #

-

Stoyan Stefanov talked at Joe Dev On Tech about React. He goes over all the features of the library and ends with a concrete example.

- -
-

JSX: E4X The Good Parts #

-

JSX is often compared to the now defunct E4X, Vjeux went over all the E4X features and explained how JSX is different and hopefully doesn't repeat the same mistakes.

- -
-

E4X (ECMAScript for XML) is a Javascript syntax extension and a runtime to manipulate XML. It was promoted by Mozilla but failed to become mainstream and is now deprecated. JSX was inspired by E4X. In this article, I'm going to go over all the features of E4X and explain the design decisions behind JSX.

- -

Historical Context

- -

E4X has been created in 2002 by John Schneider. This was the golden age of XML where it was being used for everything: data, configuration files, code, interfaces (DOM) ... E4X was first implemented inside of Rhino, a Javascript implementation from Mozilla written in Java.

- -

Continue reading ...

-
-

React + Socket.io #

-

Geert Pasteels made a small experiment with Socket.io. He wrote a very small mixin that synchronizes React state with the server. Just include this mixin to your React component and it is now live!

-
changeHandler: function (data) {
-  if (!_.isEqual(data.state, this.state) && this.path === data.path) {
-    this.setState(data.state);
-  }
-},
-componentDidMount: function (root) {
-  this.path = utils.nodePath(root);
-  socket.on('component-change', this.changeHandler);
-},
-componentWillUpdate: function (props, state) {
-  socket.emit('component-change', { path: this.path, state: state });
-},
-componentWillUnmount: function () {
-  socket.removeListener('component-change', this.change);
-}
-
-

Check it out on GitHub...

-

cssobjectify #

-

Andrey Popp implemented a source transform that takes a CSS file and converts it to JSON. This integrates pretty nicely with React.

-
/* style.css */
-MyComponent {
-  font-size: 12px;
-  background-color: red;
-}
-
-/* myapp.js */
-var React = require('react-tools/build/modules/React');
-var Styles = require('./styles.css');
-
-var MyComponent = React.createClass({
-  render: function() {
-    return (
-      <div style={Styles.MyComponent}>
-        Hello, world!
-      </div>
-    )
-  }
-});
-
-

Check it out on GitHub...

-

ngReact #

-

David Chang working at HasOffer wanted to speed up his Angular app and replaced Angular primitives by React at different layers. When using React naively it is 67% faster, but when combining it with angular's transclusion it is 450% slower.

- -
-

Rendering this takes 803ms for 10 iterations, hovering around 35 and 55ms for each data reload (that's 67% faster). You'll notice that the first load takes a little longer than successive loads, and the second load REALLY struggles - here, it's 433ms, which is more than half of the total time! -

- -

Read the full article...

-
-

vim-jsx #

-

Max Wang made a vim syntax highlighting and indentation plugin for vim.

- -
-

Syntax highlighting and indenting for JSX. JSX is a JavaScript syntax transformer which translates inline XML document fragments into JavaScript objects. It was developed by Facebook alongside React.

- -

This bundle requires pangloss's vim-javascript syntax highlighting.

- -

Vim support for inline XML in JS is remarkably similar to the same for PHP.

- -

View on GitHub...

-
-

Random Tweet #

-

- -
-
- @@ -90,6 +90,103 @@

Recent posts

+
+

Community Round-up #13

+

December 30, 2013 by Vjeux

+
+
+

Happy holidays! This blog post is a little-late Christmas present for all the React users. Hopefully it will inspire you to write awesome web apps in 2014!

+

React Touch #

+

Pete Hunt wrote three demos showing that React can be used to run 60fps native-like experiences on mobile web. A frosted glass effect, an image gallery with 3d animations and an infinite scroll view.

+ +
+ +

Try out the demos!

+

Introduction to React #

+

Stoyan Stefanov talked at Joe Dev On Tech about React. He goes over all the features of the library and ends with a concrete example.

+ +
+

JSX: E4X The Good Parts #

+

JSX is often compared to the now defunct E4X, Vjeux went over all the E4X features and explained how JSX is different and hopefully doesn't repeat the same mistakes.

+ +
+

E4X (ECMAScript for XML) is a Javascript syntax extension and a runtime to manipulate XML. It was promoted by Mozilla but failed to become mainstream and is now deprecated. JSX was inspired by E4X. In this article, I'm going to go over all the features of E4X and explain the design decisions behind JSX.

+ +

Historical Context

+ +

E4X has been created in 2002 by John Schneider. This was the golden age of XML where it was being used for everything: data, configuration files, code, interfaces (DOM) ... E4X was first implemented inside of Rhino, a Javascript implementation from Mozilla written in Java.

+ +

Continue reading ...

+
+

React + Socket.io #

+

Geert Pasteels made a small experiment with Socket.io. He wrote a very small mixin that synchronizes React state with the server. Just include this mixin to your React component and it is now live!

+
changeHandler: function (data) {
+  if (!_.isEqual(data.state, this.state) && this.path === data.path) {
+    this.setState(data.state);
+  }
+},
+componentDidMount: function (root) {
+  this.path = utils.nodePath(root);
+  socket.on('component-change', this.changeHandler);
+},
+componentWillUpdate: function (props, state) {
+  socket.emit('component-change', { path: this.path, state: state });
+},
+componentWillUnmount: function () {
+  socket.removeListener('component-change', this.change);
+}
+
+

Check it out on GitHub...

+

cssobjectify #

+

Andrey Popp implemented a source transform that takes a CSS file and converts it to JSON. This integrates pretty nicely with React.

+
/* style.css */
+MyComponent {
+  font-size: 12px;
+  background-color: red;
+}
+
+/* myapp.js */
+var React = require('react-tools/build/modules/React');
+var Styles = require('./styles.css');
+
+var MyComponent = React.createClass({
+  render: function() {
+    return (
+      <div style={Styles.MyComponent}>
+        Hello, world!
+      </div>
+    )
+  }
+});
+
+

Check it out on GitHub...

+

ngReact #

+

David Chang working at HasOffer wanted to speed up his Angular app and replaced Angular primitives by React at different layers. When using React naively it is 67% faster, but when combining it with angular's transclusion it is 450% slower.

+ +
+

Rendering this takes 803ms for 10 iterations, hovering around 35 and 55ms for each data reload (that's 67% faster). You'll notice that the first load takes a little longer than successive loads, and the second load REALLY struggles - here, it's 433ms, which is more than half of the total time! +

+ +

Read the full article...

+
+

vim-jsx #

+

Max Wang made a vim syntax highlighting and indentation plugin for vim.

+ +
+

Syntax highlighting and indenting for JSX. JSX is a JavaScript syntax transformer which translates inline XML document fragments into JavaScript objects. It was developed by Facebook alongside React.

+ +

This bundle requires pangloss's vim-javascript syntax highlighting.

+ +

Vim support for inline XML in JS is remarkably similar to the same for PHP.

+ +

View on GitHub...

+
+

Random Tweet #

+

+ +
+
+

Community Round-up #12

December 23, 2013 by Vjeux

@@ -320,123 +417,6 @@

Random Tweet

-
-

Community Round-up #10

-

November 6, 2013 by Vjeux

-
-
-

This is the 10th round-up already and React has come quite far since it was open sourced. Almost all new web projects at Khan Academy, Facebook, and Instagram are being developed using React. React has been deployed in a variety of contexts: a Chrome extension, a Windows 8 application, mobile websites, and desktop websites supporting Internet Explorer 8! Language-wise, React is not only being used within JavaScript but also CoffeeScript and ClojureScript.

- -

The best part is that no drastic changes have been required to support all those use cases. Most of the efforts were targeted at polishing edge cases, performance improvements, and documentation.

-

Khan Academy - Officially moving to React #

-

Joel Burget announced at Hack Reactor that new front-end code at Khan Academy should be written in React!

- -
-

How did we get the rest of the team to adopt React? Using interns as an attack vector! Most full-time devs had already been working on their existing projects for a while and weren't looking to try something new at the time, but our class of summer interns was just arriving. For whatever reason, a lot of them decided to try React for their projects. Then mentors became exposed through code reviews or otherwise touching the new code. In this way React knowledge diffused to almost the whole team over the summer.

- -

Since the first React checkin on June 5, we've somehow managed to accumulate 23500 lines of jsx (React-flavored js) code. Which is terrifying in a way - that's a lot of code - but also really exciting that it was picked up so quickly.

- -

We held three meetings about how we should proceed with React. At the first two we decided to continue experimenting with React and deferred a final decision on whether to adopt it. At the third we adopted the policy that new code should be written in React.

- -

I'm excited that we were able to start nudging code quality forward. However, we still have a lot of work to do! One of the selling points of this transition is adopting a uniform frontend style. We're trying to upgrade all the code from (really old) pure jQuery and (regular old) Backbone views / Handlebars to shiny React. At the moment all we've done is introduce more fragmentation. We won't be gratuitously updating working code (if it ain't broke, don't fix it), but are seeking out parts of the codebase where we can shoot two birds with one stone by rewriting in React while fixing bugs or adding functionality.

- -

Read the full article

-
-

React: Rethinking best practices #

-

Pete Hunt's talk at JSConf EU 2013 is now available in video.

- -
-

Server-side React with PHP #

-

Stoyan Stefanov's series of articles on React has two new entries on how to execute React on the server to generate the initial page load.

- -
-

This post is an initial hack to have React components render server-side in PHP.

- -
    -
  • Problem: Build web UIs
  • -
  • Solution: React
  • -
  • Problem: UI built in JS is anti-SEO (assuming search engines are still noscript) and bad for perceived performance (blank page till JS arrives)
  • -
  • Solution: React page to render the first view
  • -
  • Problem: Can't host node.js apps / I have tons of PHP code
  • -
  • Solution: Use PHP then!
  • -
- -

Read part 1 ...

- -

Read part 2 ...

- -

Rendered markup on the server: -

-
-

TodoMVC Benchmarks #

-

Webkit has a TodoMVC Benchmark that compares different frameworks. They recently included React and here are the results (average of 10 runs in Chrome 30):

- -
    -
  • AngularJS: 4043ms
  • -
  • AngularJSPerf: 3227ms
  • -
  • BackboneJS: 1874ms
  • -
  • EmberJS: 6822ms
  • -
  • jQuery: 14628ms
  • -
  • React: 2864ms
  • -
  • VanillaJS: 5567ms
  • -
- -

Try it yourself!

- -

Please don't take those numbers too seriously, they only reflect one very specific use case and are testing code that wasn't written with performance in mind.

- -

Even though React scores as one of the fastest frameworks in the benchmark, the React code is simple and idiomatic. The only performance tweak used is the following function:

-
/**
- * This is a completely optional performance enhancement that you can implement
- * on any React component. If you were to delete this method the app would still
- * work correctly (and still be very performant!), we just use it as an example
- * of how little code it takes to get an order of magnitude performance improvement.
- */
-shouldComponentUpdate: function (nextProps, nextState) {
-  return (
-    nextProps.todo.id !== this.props.todo.id ||
-    nextProps.todo !== this.props.todo ||
-    nextProps.editing !== this.props.editing ||
-    nextState.editText !== this.state.editText
-  );
-},
-
-

By default, React "re-renders" all the components when anything changes. This is usually fast enough that you don't need to care. However, you can provide a function that can tell whether there will be any change based on the previous and next states and props. If it is faster than re-rendering the component, then you get a performance improvement.

- -

The fact that you can control when components are rendered is a very important characteristic of React as it gives you control over its performance. We are going to talk more about performance in the future, stay tuned.

-

Guess the filter #

-

Connor McSheffrey implemented a small game using React. The goal is to guess which filter has been used to create the Instagram photo. -

-

React vs FruitMachine #

-

Andrew Betts, director of the Financial Times Labs, posted an article comparing FruitMachine and React.

- -
-

Eerily similar, no? Maybe Facebook was inspired by Fruit Machine (after all, we got there first), but more likely, it just shows that this is a pretty decent way to solve the problem, and great minds think alike. We're graduating to a third phase in the evolution of web best practice - from intermingling of markup, style and behaviour, through a phase in which those concerns became ever more separated and encapsulated, and finally to a model where we can do that separation at a component level. Developments like Web Components show the direction the web community is moving, and frameworks like React and Fruit Machine are in fact not a lot more than polyfills for that promised behaviour to come.

- -

Read the full article...

-
- -

Even though we weren't inspired by FruitMachine (React has been used in production since before FruitMachine was open sourced), it's great to see similar technologies emerging and becoming popular.

-

React Brunch #

-

Matthew McCray implemented react-brunch, a JSX compilation step for Brunch.

- -
-

Adds React support to brunch by automatically compiling *.jsx files.

- -

You can configure react-brunch to automatically insert a react header (/** @jsx React.DOM */) into all *.jsx files. Disabled by default.

- -

Install the plugin via npm with npm install --save react-brunch.

- -

Read more...

-
-

Random Tweet #

-

I'm going to start adding a tweet at the end of each round-up. We'll start with this one:

- - - -
-
- @@ -90,6 +90,123 @@

Recent posts

+
+

Community Round-up #10

+

November 6, 2013 by Vjeux

+
+
+

This is the 10th round-up already and React has come quite far since it was open sourced. Almost all new web projects at Khan Academy, Facebook, and Instagram are being developed using React. React has been deployed in a variety of contexts: a Chrome extension, a Windows 8 application, mobile websites, and desktop websites supporting Internet Explorer 8! Language-wise, React is not only being used within JavaScript but also CoffeeScript and ClojureScript.

+ +

The best part is that no drastic changes have been required to support all those use cases. Most of the efforts were targeted at polishing edge cases, performance improvements, and documentation.

+

Khan Academy - Officially moving to React #

+

Joel Burget announced at Hack Reactor that new front-end code at Khan Academy should be written in React!

+ +
+

How did we get the rest of the team to adopt React? Using interns as an attack vector! Most full-time devs had already been working on their existing projects for a while and weren't looking to try something new at the time, but our class of summer interns was just arriving. For whatever reason, a lot of them decided to try React for their projects. Then mentors became exposed through code reviews or otherwise touching the new code. In this way React knowledge diffused to almost the whole team over the summer.

+ +

Since the first React checkin on June 5, we've somehow managed to accumulate 23500 lines of jsx (React-flavored js) code. Which is terrifying in a way - that's a lot of code - but also really exciting that it was picked up so quickly.

+ +

We held three meetings about how we should proceed with React. At the first two we decided to continue experimenting with React and deferred a final decision on whether to adopt it. At the third we adopted the policy that new code should be written in React.

+ +

I'm excited that we were able to start nudging code quality forward. However, we still have a lot of work to do! One of the selling points of this transition is adopting a uniform frontend style. We're trying to upgrade all the code from (really old) pure jQuery and (regular old) Backbone views / Handlebars to shiny React. At the moment all we've done is introduce more fragmentation. We won't be gratuitously updating working code (if it ain't broke, don't fix it), but are seeking out parts of the codebase where we can shoot two birds with one stone by rewriting in React while fixing bugs or adding functionality.

+ +

Read the full article

+
+

React: Rethinking best practices #

+

Pete Hunt's talk at JSConf EU 2013 is now available in video.

+ +
+

Server-side React with PHP #

+

Stoyan Stefanov's series of articles on React has two new entries on how to execute React on the server to generate the initial page load.

+ +
+

This post is an initial hack to have React components render server-side in PHP.

+ +
    +
  • Problem: Build web UIs
  • +
  • Solution: React
  • +
  • Problem: UI built in JS is anti-SEO (assuming search engines are still noscript) and bad for perceived performance (blank page till JS arrives)
  • +
  • Solution: React page to render the first view
  • +
  • Problem: Can't host node.js apps / I have tons of PHP code
  • +
  • Solution: Use PHP then!
  • +
+ +

Read part 1 ...

+ +

Read part 2 ...

+ +

Rendered markup on the server: +

+
+

TodoMVC Benchmarks #

+

Webkit has a TodoMVC Benchmark that compares different frameworks. They recently included React and here are the results (average of 10 runs in Chrome 30):

+ +
    +
  • AngularJS: 4043ms
  • +
  • AngularJSPerf: 3227ms
  • +
  • BackboneJS: 1874ms
  • +
  • EmberJS: 6822ms
  • +
  • jQuery: 14628ms
  • +
  • React: 2864ms
  • +
  • VanillaJS: 5567ms
  • +
+ +

Try it yourself!

+ +

Please don't take those numbers too seriously, they only reflect one very specific use case and are testing code that wasn't written with performance in mind.

+ +

Even though React scores as one of the fastest frameworks in the benchmark, the React code is simple and idiomatic. The only performance tweak used is the following function:

+
/**
+ * This is a completely optional performance enhancement that you can implement
+ * on any React component. If you were to delete this method the app would still
+ * work correctly (and still be very performant!), we just use it as an example
+ * of how little code it takes to get an order of magnitude performance improvement.
+ */
+shouldComponentUpdate: function (nextProps, nextState) {
+  return (
+    nextProps.todo.id !== this.props.todo.id ||
+    nextProps.todo !== this.props.todo ||
+    nextProps.editing !== this.props.editing ||
+    nextState.editText !== this.state.editText
+  );
+},
+
+

By default, React "re-renders" all the components when anything changes. This is usually fast enough that you don't need to care. However, you can provide a function that can tell whether there will be any change based on the previous and next states and props. If it is faster than re-rendering the component, then you get a performance improvement.

+ +

The fact that you can control when components are rendered is a very important characteristic of React as it gives you control over its performance. We are going to talk more about performance in the future, stay tuned.

+

Guess the filter #

+

Connor McSheffrey implemented a small game using React. The goal is to guess which filter has been used to create the Instagram photo. +

+

React vs FruitMachine #

+

Andrew Betts, director of the Financial Times Labs, posted an article comparing FruitMachine and React.

+ +
+

Eerily similar, no? Maybe Facebook was inspired by Fruit Machine (after all, we got there first), but more likely, it just shows that this is a pretty decent way to solve the problem, and great minds think alike. We're graduating to a third phase in the evolution of web best practice - from intermingling of markup, style and behaviour, through a phase in which those concerns became ever more separated and encapsulated, and finally to a model where we can do that separation at a component level. Developments like Web Components show the direction the web community is moving, and frameworks like React and Fruit Machine are in fact not a lot more than polyfills for that promised behaviour to come.

+ +

Read the full article...

+
+ +

Even though we weren't inspired by FruitMachine (React has been used in production since before FruitMachine was open sourced), it's great to see similar technologies emerging and becoming popular.

+

React Brunch #

+

Matthew McCray implemented react-brunch, a JSX compilation step for Brunch.

+ +
+

Adds React support to brunch by automatically compiling *.jsx files.

+ +

You can configure react-brunch to automatically insert a react header (/** @jsx React.DOM */) into all *.jsx files. Disabled by default.

+ +

Install the plugin via npm with npm install --save react-brunch.

+ +

Read more...

+
+

Random Tweet #

+

I'm going to start adding a tweet at the end of each round-up. We'll start with this one:

+ + + +
+
+

Thinking in React

November 5, 2013 by Pete Hunt

@@ -394,68 +511,6 @@

Reactive Table -

Community Round-up #8

-

September 24, 2013 by Vjeux

-
-
-

A lot has happened in the month since our last update. Here are some of the more interesting things we've found. But first, we have a couple updates before we share links.

- -

First, we are organizing a React Hackathon in Facebook's Seattle office on Saturday September 28. If you want to hack on React, meet some of the team or win some prizes, feel free to join us!

- -

We've also reached a point where there are too many questions for us to handle directly. We're encouraging people to ask questions on StackOverflow using the tag [reactjs]. Many members of the team and community have subscribed to the tag, so feel free to ask questions there. We think these will be more discoverable than Google Groups archives or IRC logs.

-

Javascript Jabber #

-

Pete Hunt and Jordan Walke were interviewed on Javascript Jabber for an hour. They go over many aspects of React such as 60 FPS, Data binding, Performance, Diffing Algorithm, DOM Manipulation, Node.js support, server-side rendering, JSX, requestAnimationFrame and the community. This is a gold mine of information about React.

- -
-

PETE: So React was designed all around that. Conceptually, how you build a React app is that every time your data changes, it's like hitting the refresh button in a server-rendered app. What we do is we conceptually throw out all of the markup and event handlers that you've registered and we reset the whole page and then we redraw the entire page. If you're writing a server-rendered app, handling updates is really easy because you hit the refresh button and you're pretty much guaranteed to get what you expect.

- -

MERRICK: That's true. You don't get into these odd states.

- -

PETE: Exactly, exactly. In order to implement that, we communicate it as a fake DOM. What we'll do is rather than throw out the actual browser html and event handlers, we have an internal representation of what the page looks like and then we generate a brand new representation of what we want the page to look like. Then we perform this really, really fast diffing algorithm between those two page representations, DOM representations. Then React will compute the minimum set of DOM mutations it needs to make to bring the page up to date.

- -

Then to finally get to answer your question, that set of DOM mutations then goes into a queue and we can plug in arbitrary flushing strategies for that. For example, when we originally launched React in open source, every setState would immediately trigger a flush to the DOM. That wasn't part of the contract of setState, but that was just our strategy and it worked pretty well. Then this totally awesome open source contributor Ben Alpert at Khan Academy built a new batching strategy which would basically queue up every single DOM update and state change that happened within an event tick and would execute them in bulk at the end of the event tick.

- -

Read the full conversation ...

-
-

JSXTransformer Trick #

-

While this is not going to work for all the attributes since they are camelCased in React, this is a pretty cool trick.

- -
- - -

Remarkable React #

-

Stoyan Stefanov gave a talk at BrazilJS about React and wrote an article with the content of the presentation. He goes through the difficulties of writting active apps using the DOM API and shows how React handles it.

- -
-

So how does exactly React deal with it internally? Two crazy ideas - virtual DOM and synthetic events.

- -

You define you components in React. It builds a virtual DOM in JavaScript land which is way more efficient. Then it updates the DOM. (And "virtual DOM" is a very big name for what is simply a JavaScript object with nested key-value pairs)

- -

Data changes. React computes a diff (in JavaScript land, which is, of course, much more efficient) and updates the single table cell that needs to change. React replicates the state of the virtual DOM into the actual DOM only when and where it's necessary. And does it all at once, in most cases in a single tick of the requestAnimationFrame().

- -

What about event handlers? They are synthetic. React uses event delegation to listen way at the top of the React tree. So removing a node in the virtual DOM has no effect on the event handling.

- -

The events are automatically cross-browser (they are React events). They are also much closer to W3C than any browser. That means that for example e.target works, no need to look for the event object or checking whether it's e.target or e.srcElement (IE). Bubbling and capturing phases also work cross browser. React also takes the liberty of making some small fixes, e.g. the event <input onChange> fires when you type, not when blur away from the input. And of course, event delegation is used as the most efficient way to handle events. You know that "thou shall use event delegation" is also commonly given advice for making web apps snappy.

- -

The good thing about the virtual DOM is that it's all in JavaScript land. You build all your UI in JavaScript. Which means it can be rendered on the server side, so you initial view is fast (and any SEO concerns are addressed). Also, if there are especially heavy operations they can be threaded into WebWorkers, which otherwise have no DOM access.

- -

Read More ...

-
-

Markdown in React #

-

Ben Alpert converted marked, a Markdown Javascript implementation, in React: marked-react. Even without using JSX, the HTML generation is now a lot cleaner. It is also safer as forgetting a call to escape will not introduce an XSS vulnerability. -

-

Unite from BugBusters #

-

Renault John Lecoultre wrote Unite, an interactive tool for analyzing code dynamically using React. It integrates with CodeMirror. -

-

#reactjs IRC Logs #

-

Vjeux re-implemented the display part of the IRC logger in React. Just 130 lines are needed for a performant infinite scroll with timestamps and color-coded author names.

- - - -
-

- @@ -90,6 +90,68 @@

Recent posts

+
+

Community Round-up #8

+

September 24, 2013 by Vjeux

+
+
+

A lot has happened in the month since our last update. Here are some of the more interesting things we've found. But first, we have a couple updates before we share links.

+ +

First, we are organizing a React Hackathon in Facebook's Seattle office on Saturday September 28. If you want to hack on React, meet some of the team or win some prizes, feel free to join us!

+ +

We've also reached a point where there are too many questions for us to handle directly. We're encouraging people to ask questions on StackOverflow using the tag [reactjs]. Many members of the team and community have subscribed to the tag, so feel free to ask questions there. We think these will be more discoverable than Google Groups archives or IRC logs.

+

Javascript Jabber #

+

Pete Hunt and Jordan Walke were interviewed on Javascript Jabber for an hour. They go over many aspects of React such as 60 FPS, Data binding, Performance, Diffing Algorithm, DOM Manipulation, Node.js support, server-side rendering, JSX, requestAnimationFrame and the community. This is a gold mine of information about React.

+ +
+

PETE: So React was designed all around that. Conceptually, how you build a React app is that every time your data changes, it's like hitting the refresh button in a server-rendered app. What we do is we conceptually throw out all of the markup and event handlers that you've registered and we reset the whole page and then we redraw the entire page. If you're writing a server-rendered app, handling updates is really easy because you hit the refresh button and you're pretty much guaranteed to get what you expect.

+ +

MERRICK: That's true. You don't get into these odd states.

+ +

PETE: Exactly, exactly. In order to implement that, we communicate it as a fake DOM. What we'll do is rather than throw out the actual browser html and event handlers, we have an internal representation of what the page looks like and then we generate a brand new representation of what we want the page to look like. Then we perform this really, really fast diffing algorithm between those two page representations, DOM representations. Then React will compute the minimum set of DOM mutations it needs to make to bring the page up to date.

+ +

Then to finally get to answer your question, that set of DOM mutations then goes into a queue and we can plug in arbitrary flushing strategies for that. For example, when we originally launched React in open source, every setState would immediately trigger a flush to the DOM. That wasn't part of the contract of setState, but that was just our strategy and it worked pretty well. Then this totally awesome open source contributor Ben Alpert at Khan Academy built a new batching strategy which would basically queue up every single DOM update and state change that happened within an event tick and would execute them in bulk at the end of the event tick.

+ +

Read the full conversation ...

+
+

JSXTransformer Trick #

+

While this is not going to work for all the attributes since they are camelCased in React, this is a pretty cool trick.

+ +
+ + +

Remarkable React #

+

Stoyan Stefanov gave a talk at BrazilJS about React and wrote an article with the content of the presentation. He goes through the difficulties of writting active apps using the DOM API and shows how React handles it.

+ +
+

So how does exactly React deal with it internally? Two crazy ideas - virtual DOM and synthetic events.

+ +

You define you components in React. It builds a virtual DOM in JavaScript land which is way more efficient. Then it updates the DOM. (And "virtual DOM" is a very big name for what is simply a JavaScript object with nested key-value pairs)

+ +

Data changes. React computes a diff (in JavaScript land, which is, of course, much more efficient) and updates the single table cell that needs to change. React replicates the state of the virtual DOM into the actual DOM only when and where it's necessary. And does it all at once, in most cases in a single tick of the requestAnimationFrame().

+ +

What about event handlers? They are synthetic. React uses event delegation to listen way at the top of the React tree. So removing a node in the virtual DOM has no effect on the event handling.

+ +

The events are automatically cross-browser (they are React events). They are also much closer to W3C than any browser. That means that for example e.target works, no need to look for the event object or checking whether it's e.target or e.srcElement (IE). Bubbling and capturing phases also work cross browser. React also takes the liberty of making some small fixes, e.g. the event <input onChange> fires when you type, not when blur away from the input. And of course, event delegation is used as the most efficient way to handle events. You know that "thou shall use event delegation" is also commonly given advice for making web apps snappy.

+ +

The good thing about the virtual DOM is that it's all in JavaScript land. You build all your UI in JavaScript. Which means it can be rendered on the server side, so you initial view is fast (and any SEO concerns are addressed). Also, if there are especially heavy operations they can be threaded into WebWorkers, which otherwise have no DOM access.

+ +

Read More ...

+
+

Markdown in React #

+

Ben Alpert converted marked, a Markdown Javascript implementation, in React: marked-react. Even without using JSX, the HTML generation is now a lot cleaner. It is also safer as forgetting a call to escape will not introduce an XSS vulnerability. +

+

Unite from BugBusters #

+

Renault John Lecoultre wrote Unite, an interactive tool for analyzing code dynamically using React. It integrates with CodeMirror. +

+

#reactjs IRC Logs #

+

Vjeux re-implemented the display part of the IRC logger in React. Just 130 lines are needed for a performant infinite scroll with timestamps and color-coded author names.

+ + + +
+
+

Community Round-up #7

August 26, 2013 by Vjeux

@@ -323,31 +385,6 @@

Installation

-
-

React v0.4.1

-

July 26, 2013 by Paul O'Shannessy

-
-
-

React v0.4.1 is a small update, mostly containing correctness fixes. Some code has been restructured internally but those changes do not impact any of our public APIs.

-

React #

-
    -
  • setState callbacks are now executed in the scope of your component.
  • -
  • click events now work on Mobile Safari.
  • -
  • Prevent a potential error in event handling if Object.prototype is extended.
  • -
  • Don't set DOM attributes to the string "undefined" on update when previously defined.
  • -
  • Improved support for <iframe> attributes.
  • -
  • Added checksums to detect and correct cases where server-side rendering markup mismatches what React expects client-side.
  • -
-

JSXTransformer #

-
    -
  • Improved environment detection so it can be run in a non-browser environment.
  • -
- -

Download it now!

- -
-
- @@ -90,6 +90,31 @@

Recent posts

+
+

React v0.4.1

+

July 26, 2013 by Paul O'Shannessy

+
+
+

React v0.4.1 is a small update, mostly containing correctness fixes. Some code has been restructured internally but those changes do not impact any of our public APIs.

+

React #

+
    +
  • setState callbacks are now executed in the scope of your component.
  • +
  • click events now work on Mobile Safari.
  • +
  • Prevent a potential error in event handling if Object.prototype is extended.
  • +
  • Don't set DOM attributes to the string "undefined" on update when previously defined.
  • +
  • Improved support for <iframe> attributes.
  • +
  • Added checksums to detect and correct cases where server-side rendering markup mismatches what React expects client-side.
  • +
+

JSXTransformer #

+
    +
  • Improved environment detection so it can be run in a non-browser environment.
  • +
+ +

Download it now!

+ +
+
+

Community Round-up #5

July 23, 2013 by Vjeux

@@ -349,46 +374,6 @@

Snake in React -

New in React v0.4: Autobind by Default

-

July 2, 2013 by Paul O'Shannessy

-
-
-

React v0.4 is very close to completion. As we finish it off, we'd like to share with you some of the major changes we've made since v0.3. This is the first of several posts we'll be making over the next week.

-

What is React.autoBind? #

-

If you take a look at most of our current examples, you'll see us using React.autoBind for event handlers. This is used in place of Function.prototype.bind. Remember that in JS, function calls are late-bound. That means that if you simply pass a function around, the this used inside won't necessarily be the this you expect. Function.prototype.bind creates a new, properly bound, function so that when called, this is exactly what you expect it to be.

- -

Before we launched React, we would write this:

-
React.createClass({
-  onClick: function(event) {/* do something with this */},
-  render: function() {
-    return <button onClick={this.onClick.bind(this)} />;
-  }
-});
-
-

We wrote React.autoBind as a way to cache the function creation and save on memory usage. Since render can get called multiple times, if you used this.onClick.bind(this) you would actually create a new function on each pass. With React v0.3 you were able to write this instead:

-
React.createClass({
-  onClick: React.autoBind(function(event) {/* do something with this */}),
-  render: function() {
-    return <button onClick={this.onClick} />;
-  }
-});
-

What's Changing in v0.4? #

-

After using React.autoBind for a few weeks, we realized that there were very few times that we didn't want that behavior. So we made it the default! Now all methods defined within React.createClass will already be bound to the correct instance.

- -

Starting with v0.4 you can just write this:

-
React.createClass({
-  onClick: function(event) {/* do something with this */},
-  render: function() {
-    return <button onClick={this.onClick} />;
-  }
-});
-
-

For v0.4 we will simply be making React.autoBind a no-op — it will just return the function you pass to it. Most likely you won't have to change your code to account for this change, though we encourage you to update. We'll publish a migration guide documenting this and other changes that come along with React v0.4.

- -
-

-