diff --git a/blog/2013/06/02/jsfiddle-integration.html b/blog/2013/06/02/jsfiddle-integration.html index 086696ef2b..98f8b9ac68 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 791f6eefae..9fdfb047c2 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 9bbea1830d..0189d6b3e3 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 db95fbf75f..f2d56559d6 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 d06c237b6e..4fe07f5c0a 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 4b72091005..19ecfa72f8 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 695d96bc5f..0a6543dd0c 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 20d2770191..8465b40482 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 86e34640d0..0bc070ae3a 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 e38bcb044d..fa4c314065 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 3c43e98718..062f7a6161 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 3f08d6cacf..a3eb08b3ea 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 009e5c728b..1d3a9c7712 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 ba6f2a2c16..39e7f67d39 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 b26e3118c0..e8ec099cba 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 6eb2e2a1fb..56bb23b7e9 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 85c044607e..a425b7a894 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 a7f4e03d9d..1b07a25b11 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 2e2812b7e9..4a099db230 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 dc996f2660..34460bf935 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 4e2a78feaa..608b552c06 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 f1afdf6ec9..550d28c234 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 a76262892f..03b399e25d 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 14842f1771..dff7d8f8a9 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 0050969330..40d537f657 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 edaa54c730..277a699e3a 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 5e3d56f0b4..3e5f8f8010 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 973f07600e..c49e85ec8a 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 70355e0eb3..8187f8e3c9 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 0586fcad00..8da32c405b 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 74708bdad5..978c41bff0 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 58cdf0a2cd..14b56b664a 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 9d37cbde40..71a7d56206 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 7297812d6f..9c79398417 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 80f7647c1d..ba8c088c45 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 70809be930..3595423f6b 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 88f6f22b2d..112d8067d0 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 c1f66752f9..fec1039184 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 face193804..9f580e22ad 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 07c7f6aef6..f1d885698c 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 0e7b471be8..fb89832808 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 9ef2c60aac..f89195f828 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 42ec60ff97..04dc7e3a76 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 5310950573..383b50c122 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 90db2cb23b..00a4183fa3 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 d0dfb82554..58b952d82f 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 4a54bae6a1..e30c2ba705 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 cb87f7793e..05d285a768 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 19bf815026..e59a2f3322 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 ed35cdaef7..bec16ae844 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 98e3283c9d..2679d44fd0 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 index f3c2a9abb8..37e962402a 100644 --- a/blog/2014/09/24/testing-flux-applications.html +++ b/blog/2014/09/24/testing-flux-applications.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/10/14/introducing-react-elements.html b/blog/2014/10/14/introducing-react-elements.html index 8e3ffb1aec..bc90e7a3cb 100644 --- a/blog/2014/10/14/introducing-react-elements.html +++ b/blog/2014/10/14/introducing-react-elements.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/10/16/react-v0.12-rc1.html b/blog/2014/10/16/react-v0.12-rc1.html index 61c7fcb00e..ce1dd293d8 100644 --- a/blog/2014/10/16/react-v0.12-rc1.html +++ b/blog/2014/10/16/react-v0.12-rc1.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/10/17/community-roundup-23.html b/blog/2014/10/17/community-roundup-23.html index 572707e8bf..ad0a2a71a0 100644 --- a/blog/2014/10/17/community-roundup-23.html +++ b/blog/2014/10/17/community-roundup-23.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/10/27/react-js-conf.html b/blog/2014/10/27/react-js-conf.html index 0d493933eb..43e4fc8d84 100644 --- a/blog/2014/10/27/react-js-conf.html +++ b/blog/2014/10/27/react-js-conf.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/10/28/react-v0.12.html b/blog/2014/10/28/react-v0.12.html index e4383e7ae1..c0f3556833 100644 --- a/blog/2014/10/28/react-v0.12.html +++ b/blog/2014/10/28/react-v0.12.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/11/24/react-js-conf-updates.html b/blog/2014/11/24/react-js-conf-updates.html index 73971577c4..82ef0dfb8b 100644 --- a/blog/2014/11/24/react-js-conf-updates.html +++ b/blog/2014/11/24/react-js-conf-updates.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/11/25/community-roundup-24.html b/blog/2014/11/25/community-roundup-24.html index d0ff9351bf..efe3a81e78 100644 --- a/blog/2014/11/25/community-roundup-24.html +++ b/blog/2014/11/25/community-roundup-24.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/12/18/react-v0.12.2.html b/blog/2014/12/18/react-v0.12.2.html index 2f5bf9e0fb..ba091cf459 100644 --- a/blog/2014/12/18/react-v0.12.2.html +++ b/blog/2014/12/18/react-v0.12.2.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2014/12/19/react-js-conf-diversity-scholarship.html b/blog/2014/12/19/react-js-conf-diversity-scholarship.html index 1e658b1bb2..4f47ba0a8e 100644 --- a/blog/2014/12/19/react-js-conf-diversity-scholarship.html +++ b/blog/2014/12/19/react-js-conf-diversity-scholarship.html @@ -63,6 +63,8 @@

Recent posts

diff --git a/blog/2015/01/27/react-v0.13.0-beta-1.html b/blog/2015/01/27/react-v0.13.0-beta-1.html new file mode 100644 index 0000000000..da720a748c --- /dev/null +++ b/blog/2015/01/27/react-v0.13.0-beta-1.html @@ -0,0 +1,252 @@ + + + + + + + React v0.13.0 Beta 1 | React + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+ + +
+

React v0.13.0 Beta 1

+

January 27, 2015 by Sebastian Markbåge

+ +
+ +
+

React 0.13 has a lot of nice features but there is one particular feature that I'm really excited about. I couldn't wait for React.js Conf to start tomorrow morning.

+ +

Maybe you're like me and staying up late excited about the conference, or maybe you weren't one of the lucky ones to get a ticket. Either way I figured I'd give you all something to play with until then.

+ +

We just published a beta version of React v0.13.0 to npm! You can install it with npm install react@0.13.0-beta.1. Since this is a pre-release, we don't have proper release notes ready.

+ +

So what is that one feature I'm so excited about that I just couldn't wait to share?

+

Plain JavaScript Classes!! #

+

JavaScript originally didn't have a built-in class system. Every popular framework built their own, and so did we. This means that you have a learn slightly different semantics for each framework.

+ +

We figured that we're not in the business of designing a class system. We just want to use whatever is the idiomatic JavaScript way of creating classes.

+ +

In React 0.13.0 you no longer need to use React.createClass to create React components. If you have a transpiler you can use ES6 classes today. You can use the transpiler we ship with react-tools by making use of the harmony option: jsx --harmony.

+

ES6 Classes #

class HelloMessage extends React.Component {
+  render() {
+    return <div>Hello {this.props.name}</div>;
+  }
+}
+
+React.render(<HelloMessage name="Sebastian" />, mountNode);
+
+

The API is mostly what you would expect, which the exception for getInitialState. We figured that the idiomatic way to specify class state is to just use a simple instance property. Likewise getDefaultProps and propTypes are really just properties on the constructor.

+
export class Counter extends React.Component {
+  constructor(props) {
+    super(props);
+    this.state = {count: props.initialCount};
+  }
+  tick() {
+    this.setState({count: this.state.count + 1});
+  }
+  render() {
+    return (
+      <div onClick={this.tick.bind(this)}>
+        Clicks: {this.state.count}
+      </div>
+    );
+  }
+}
+Counter.propTypes = { initialCount: React.PropTypes.number };
+Counter.defaultProps = { initialCount: 0 };
+

ES7+ Property Initializers #

+

Wait, assigning to properties seems like a very imperative way of defining classes! You're right, however, we designed it this way because it's idiomatic. We fully expect a more declarative syntax for property initialization to arrive in future version of JavaScript. It might look something like this:

+
// Future Version
+export class Counter extends React.Component {
+  propTypes = { initialCount: React.PropTypes.number };
+  defaultProps = { initialCount: 0 };
+  state = { count: this.props.initialCount };
+  tick() {
+    this.setState({ count: this.state.count + 1 });
+  }
+  render() {
+    return (
+      <div onClick={this.tick.bind(this)}>
+        Clicks: {this.state.count}
+      </div>
+    );
+  }
+}
+
+

This was inspired by TypeScript's property initializers.

+

Autobinding #

+

React.createClass has a built-in magic feature that bound all methods to this automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.

+ +

Therefore we decided not to have this built-in into React's class model. You can still explicitly prebind methods in your constructor if you want.

+
class Counter extends React.Component {
+  constructor() {
+    super();
+    this.tick = this.tick.bind(this);
+  }
+  tick() {
+    ...
+  }
+  ...
+}
+
+

However, when we have the future property initializers, there is a neat trick that you can use to accomplish this syntactically:

+
class Counter extends React.Component {
+  tick = () => {
+    ...
+  }
+  ...
+}
+

Mixins #

+

Unfortunately, we will not launch any mixin support for ES6 classes in React. That would defeat the purpose of only using idiomatic JavaScript concepts.

+ +

There is no standard and universal way to define mixins in JavaScript. In fact, several features to support mixins was dropped from ES6 today. There are a lot of libraries with different semantics. We think that there should be one way of defining mixins that you can use for any JavaScript class. Us making another standard doesn't help that effort.

+ +

Therefore, we will keep working with the larger JS community to create a standard for mixins. We will also start designing a new compositional API that will help make common tasks easier to do without mixins. E.g. first-class subscriptions to any kind of Flux store.

+ +

Luckily, if you want to keep using mixins, you can just keep using React.createClass.

+ +
+

Note:

+ +

The classic React.createClass style of creating classes will continue to work just fine.

+
+

Other Languages! #

+

Since these classes are just plain old JavaScript classes, you can use other languages that compile to JavaScript classes, such as TypeScript.

+ +

You can also use CoffeeScript classes:

+
div = React.createFactory('div')
+
+class Counter extends React.Component
+  @propTypes =
+    initialCount: React.PropTypes.number
+  @defaultProps =
+    initialCount: 0
+  constructor: ->
+    @state =
+      count: this.props.initialCount
+  tick: =>
+    @setState(count: @state.count + 1)
+  render: ->
+    div(onClick: @tick, 'Clicks: ', this.state.count)
+
+
+ +
+
+
+ + + +
+
+ + + + diff --git a/blog/all.html b/blog/all.html index f260367272..e2f3f39330 100644 --- a/blog/all.html +++ b/blog/all.html @@ -61,6 +61,8 @@

All Posts

+

React v0.13.0 Beta 1 on January 27, 2015 by Sebastian Markbåge

+

React.js Conf Diversity Scholarship on December 19, 2014 by Paul O’Shannessy

React v0.12.2 on December 18, 2014 by Paul O’Shannessy

diff --git a/blog/index.html b/blog/index.html index 54fb2f48e5..0298d5cfda 100644 --- a/blog/index.html +++ b/blog/index.html @@ -63,6 +63,8 @@

Recent posts

@@ -90,6 +90,129 @@
+
+

React v0.13.0 Beta 1

+

January 27, 2015 by Sebastian Markbåge

+
+
+

React 0.13 has a lot of nice features but there is one particular feature that I'm really excited about. I couldn't wait for React.js Conf to start tomorrow morning.

+ +

Maybe you're like me and staying up late excited about the conference, or maybe you weren't one of the lucky ones to get a ticket. Either way I figured I'd give you all something to play with until then.

+ +

We just published a beta version of React v0.13.0 to npm! You can install it with npm install react@0.13.0-beta.1. Since this is a pre-release, we don't have proper release notes ready.

+ +

So what is that one feature I'm so excited about that I just couldn't wait to share?

+

Plain JavaScript Classes!! #

+

JavaScript originally didn't have a built-in class system. Every popular framework built their own, and so did we. This means that you have a learn slightly different semantics for each framework.

+ +

We figured that we're not in the business of designing a class system. We just want to use whatever is the idiomatic JavaScript way of creating classes.

+ +

In React 0.13.0 you no longer need to use React.createClass to create React components. If you have a transpiler you can use ES6 classes today. You can use the transpiler we ship with react-tools by making use of the harmony option: jsx --harmony.

+

ES6 Classes #

class HelloMessage extends React.Component {
+  render() {
+    return <div>Hello {this.props.name}</div>;
+  }
+}
+
+React.render(<HelloMessage name="Sebastian" />, mountNode);
+
+

The API is mostly what you would expect, which the exception for getInitialState. We figured that the idiomatic way to specify class state is to just use a simple instance property. Likewise getDefaultProps and propTypes are really just properties on the constructor.

+
export class Counter extends React.Component {
+  constructor(props) {
+    super(props);
+    this.state = {count: props.initialCount};
+  }
+  tick() {
+    this.setState({count: this.state.count + 1});
+  }
+  render() {
+    return (
+      <div onClick={this.tick.bind(this)}>
+        Clicks: {this.state.count}
+      </div>
+    );
+  }
+}
+Counter.propTypes = { initialCount: React.PropTypes.number };
+Counter.defaultProps = { initialCount: 0 };
+

ES7+ Property Initializers #

+

Wait, assigning to properties seems like a very imperative way of defining classes! You're right, however, we designed it this way because it's idiomatic. We fully expect a more declarative syntax for property initialization to arrive in future version of JavaScript. It might look something like this:

+
// Future Version
+export class Counter extends React.Component {
+  propTypes = { initialCount: React.PropTypes.number };
+  defaultProps = { initialCount: 0 };
+  state = { count: this.props.initialCount };
+  tick() {
+    this.setState({ count: this.state.count + 1 });
+  }
+  render() {
+    return (
+      <div onClick={this.tick.bind(this)}>
+        Clicks: {this.state.count}
+      </div>
+    );
+  }
+}
+
+

This was inspired by TypeScript's property initializers.

+

Autobinding #

+

React.createClass has a built-in magic feature that bound all methods to this automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.

+ +

Therefore we decided not to have this built-in into React's class model. You can still explicitly prebind methods in your constructor if you want.

+
class Counter extends React.Component {
+  constructor() {
+    super();
+    this.tick = this.tick.bind(this);
+  }
+  tick() {
+    ...
+  }
+  ...
+}
+
+

However, when we have the future property initializers, there is a neat trick that you can use to accomplish this syntactically:

+
class Counter extends React.Component {
+  tick = () => {
+    ...
+  }
+  ...
+}
+

Mixins #

+

Unfortunately, we will not launch any mixin support for ES6 classes in React. That would defeat the purpose of only using idiomatic JavaScript concepts.

+ +

There is no standard and universal way to define mixins in JavaScript. In fact, several features to support mixins was dropped from ES6 today. There are a lot of libraries with different semantics. We think that there should be one way of defining mixins that you can use for any JavaScript class. Us making another standard doesn't help that effort.

+ +

Therefore, we will keep working with the larger JS community to create a standard for mixins. We will also start designing a new compositional API that will help make common tasks easier to do without mixins. E.g. first-class subscriptions to any kind of Flux store.

+ +

Luckily, if you want to keep using mixins, you can just keep using React.createClass.

+ +
+

Note:

+ +

The classic React.createClass style of creating classes will continue to work just fine.

+
+

Other Languages! #

+

Since these classes are just plain old JavaScript classes, you can use other languages that compile to JavaScript classes, such as TypeScript.

+ +

You can also use CoffeeScript classes:

+
div = React.createFactory('div')
+
+class Counter extends React.Component
+  @propTypes =
+    initialCount: React.PropTypes.number
+  @defaultProps =
+    initialCount: 0
+  constructor: ->
+    @state =
+      count: this.props.initialCount
+  tick: =>
+    @setState(count: @state.count + 1)
+  render: ->
+    div(onClick: @tick, 'Clicks: ', this.state.count)
+
+
+
+

React.js Conf Diversity Scholarship

December 19, 2014 by Paul O’Shannessy

@@ -297,127 +420,6 @@ until the next conference. All the talks will be recorded and put online shortly
-
-

React v0.12

-

October 28, 2014 by Paul O’Shannessy

-
-
-

We're happy to announce the availability of React v0.12! After over a week of baking as the release candidate, we uncovered and fixed a few small issues. Thanks to all of you who upgraded and gave us feedback!

- -

We have talked a lot about some of the bigger changes in this release. We introduced new terminology and changed APIs to clean up and simplify some of the concepts of React. We also made several changes to JSX and deprecated a few functions. We won't go into depth about these changes again but we encourage you to read up on these changes in the linked posts. We'll summarize these changes and discuss some of the other changes and how they may impact you below. As always, a full changelog is also included below.

- -

The release is available for download:

- - - -

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

-

New Terminology & Updated APIs #

-

v0.12 is bringing about some new terminology. We introduced this 2 weeks ago and we've also documented it in a new section of the documentation. As a part of this, we also corrected many of our top-level APIs to align with the terminology. Component has been removed from all of our React.render* methods. While at one point the argument you passed to these functions was called a Component, it no longer is. You are passing ReactElements. To align with render methods in your component classes, we decided to keep the top-level functions short and sweet. React.renderComponent is now React.render.

- -

We also corrected some other misnomers. React.isValidComponent actually determines if the argument is a ReactElement, so it has been renamed to React.isValidElement. In the same vein, React.PropTypes.component is now React.PropTypes.element and React.PropTypes.renderable is now React.PropTypes.node.

- -

The old methods will still work but will warn upon first use. They will be removed in v0.13.

-

JSX Changes #

-

We talked more in depth about these before, so here are the highlights.

- - -

DevTools Improvements, No More __internals #

-

For months we've gotten complaints about the React DevTools message. It shouldn't have logged the up-sell message when you were already using the DevTools. Unfortunately this was because the way we implemented these tools resulted in the DevTools knowing about React, but not the reverse. We finally gave this some attention and enabled React to know if the DevTools are installed. We released an update to the devtools several weeks ago making this possible. Extensions in Chrome should auto-update so you probably already have the update installed!

- -

As a result of this update, we no longer need to expose several internal modules to the world. If you were taking advantage of this implementation detail, your code will break. React.__internals is no more.

-

License Change - BSD #

-

We updated the license on React to the BSD 3-Clause license with an explicit patent grant. Previously we used the Apache 2 license. These licenses are very similar and our extra patent grant is equivalent to the grant provided in the Apache license. You can still use React with the confidence that we have granted the use of any patents covering it. This brings us in line with the same licensing we use across the majority of our open source projects at Facebook.

- -

You can read the full text of the LICENSE and PATENTS files on GitHub.

- -
-

Changelog #

React Core #

Breaking Changes #

- -

New Features #

- -

Deprecations #

- -

Bug Fixes #

- -

React With Addons #

New Features #

- -

Breaking Changes #

- -

Bug Fixes #

- -

JSX #

Breaking Changes #

- -

New Features #

- -

Bug Fixes #

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

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

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 #

- -

JSXTransformer #

- - -

Download it now!

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

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 @@ If you were using React without JSX previously, your code should still work.
-
-

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.

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

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

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

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 3cdddc28a7..9b870e01b0 100644 --- a/blog/page2/index.html +++ b/blog/page2/index.html @@ -63,6 +63,8 @@

Recent posts

@@ -90,6 +90,127 @@
+
+

React v0.12

+

October 28, 2014 by Paul O’Shannessy

+
+
+

We're happy to announce the availability of React v0.12! After over a week of baking as the release candidate, we uncovered and fixed a few small issues. Thanks to all of you who upgraded and gave us feedback!

+ +

We have talked a lot about some of the bigger changes in this release. We introduced new terminology and changed APIs to clean up and simplify some of the concepts of React. We also made several changes to JSX and deprecated a few functions. We won't go into depth about these changes again but we encourage you to read up on these changes in the linked posts. We'll summarize these changes and discuss some of the other changes and how they may impact you below. As always, a full changelog is also included below.

+ +

The release is available for download:

+ + + +

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

+

New Terminology & Updated APIs #

+

v0.12 is bringing about some new terminology. We introduced this 2 weeks ago and we've also documented it in a new section of the documentation. As a part of this, we also corrected many of our top-level APIs to align with the terminology. Component has been removed from all of our React.render* methods. While at one point the argument you passed to these functions was called a Component, it no longer is. You are passing ReactElements. To align with render methods in your component classes, we decided to keep the top-level functions short and sweet. React.renderComponent is now React.render.

+ +

We also corrected some other misnomers. React.isValidComponent actually determines if the argument is a ReactElement, so it has been renamed to React.isValidElement. In the same vein, React.PropTypes.component is now React.PropTypes.element and React.PropTypes.renderable is now React.PropTypes.node.

+ +

The old methods will still work but will warn upon first use. They will be removed in v0.13.

+

JSX Changes #

+

We talked more in depth about these before, so here are the highlights.

+ +
    +
  • No more /** @jsx React.DOM */!
  • +
  • We no longer transform to a straight function call. <Component/> now becomes React.createElement(Component)
  • +
  • DOM components don't make use of React.DOM, instead we pass the tag name directly. <div/> becomes React.createElement('div')
  • +
  • We introduced spread attributes as a quick way to transfer props.
  • +
+

DevTools Improvements, No More __internals #

+

For months we've gotten complaints about the React DevTools message. It shouldn't have logged the up-sell message when you were already using the DevTools. Unfortunately this was because the way we implemented these tools resulted in the DevTools knowing about React, but not the reverse. We finally gave this some attention and enabled React to know if the DevTools are installed. We released an update to the devtools several weeks ago making this possible. Extensions in Chrome should auto-update so you probably already have the update installed!

+ +

As a result of this update, we no longer need to expose several internal modules to the world. If you were taking advantage of this implementation detail, your code will break. React.__internals is no more.

+

License Change - BSD #

+

We updated the license on React to the BSD 3-Clause license with an explicit patent grant. Previously we used the Apache 2 license. These licenses are very similar and our extra patent grant is equivalent to the grant provided in the Apache license. You can still use React with the confidence that we have granted the use of any patents covering it. This brings us in line with the same licensing we use across the majority of our open source projects at Facebook.

+ +

You can read the full text of the LICENSE and PATENTS files on GitHub.

+ +
+

Changelog #

React Core #

Breaking Changes #

+
    +
  • key and ref moved off props object, now accessible on the element directly
  • +
  • React is now BSD licensed with accompanying Patents grant
  • +
  • Default prop resolution has moved to Element creation time instead of mount time, making them effectively static
  • +
  • React.__internals is removed - it was exposed for DevTools which no longer needs access
  • +
  • Composite Component functions can no longer be called directly - they must be wrapped with React.createFactory first. This is handled for you when using JSX.
  • +
+

New Features #

+
    +
  • Spread operator ({...}) introduced to deprecate this.transferPropsTo
  • +
  • Added support for more HTML attributes: acceptCharset, classID, manifest
  • +
+

Deprecations #

+
    +
  • React.renderComponent --> React.render
  • +
  • React.renderComponentToString --> React.renderToString
  • +
  • React.renderComponentToStaticMarkup --> React.renderToStaticMarkup
  • +
  • React.isValidComponent --> React.isValidElement
  • +
  • React.PropTypes.component --> React.PropTypes.element
  • +
  • React.PropTypes.renderable --> React.PropTypes.node
  • +
  • DEPRECATED React.isValidClass
  • +
  • DEPRECATED instance.transferPropsTo
  • +
  • DEPRECATED Returning false from event handlers to preventDefault
  • +
  • DEPRECATED Convenience Constructor usage as function, instead wrap with React.createFactory
  • +
  • DEPRECATED use of key={null} to assign implicit keys
  • +
+

Bug Fixes #

+
    +
  • Better handling of events and updates in nested results, fixing value restoration in "layered" controlled components
  • +
  • Correctly treat event.getModifierState as case sensitive
  • +
  • Improved normalization of event.charCode
  • +
  • Better error stacks when involving autobound methods
  • +
  • Removed DevTools message when the DevTools are installed
  • +
  • Correctly detect required language features across browsers
  • +
  • Fixed support for some HTML attributes: + +
      +
    • list updates correctly now
    • +
    • scrollLeft, scrollTop removed, these should not be specified as props
    • +
  • +
  • Improved error messages
  • +
+

React With Addons #

New Features #

+
    +
  • React.addons.batchedUpdates added to API for hooking into update cycle
  • +
+

Breaking Changes #

+
    +
  • React.addons.update uses assign instead of copyProperties which does hasOwnProperty checks. Properties on prototypes will no longer be updated correctly.
  • +
+

Bug Fixes #

+
    +
  • Fixed some issues with CSS Transitions
  • +
+

JSX #

Breaking Changes #

+
    +
  • Enforced convention: lower case tag names are always treated as HTML tags, upper case tag names are always treated as composite components
  • +
  • JSX no longer transforms to simple function calls
  • +
+

New Features #

+
    +
  • @jsx React.DOM no longer required
  • +
  • spread ({...}) operator introduced to allow easier use of props
  • +
+

Bug Fixes #

+
    +
  • JSXTransformer: Make sourcemaps an option when using APIs directly (eg, for react-rails)
  • +
+ +
+
+

React.js Conf

October 27, 2014 by Vjeux

@@ -491,278 +612,6 @@ Minified build for production: -

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 dependencies 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');
-

Putting it All Together #

-

The example Flux TodoMVC application has been updated with an example test for the TodoStore, but let'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 documentation.

-

Further Reading #

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

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 dependencies 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');
+

Putting it All Together #

+

The example Flux TodoMVC application has been updated with an example test for the TodoStore, but let'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 documentation.

+

Further Reading #

+ + +
+
+

React v0.11.2

September 16, 2014 by Paul O’Shannessy

@@ -339,40 +611,6 @@ This is not the intended way to use React but can be useful as last resort if yo
-
-

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,40 @@
+
+

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 @@ Minified build for production: -

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

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 @@ report bugs on GitHub.

-
-

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

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 @@ Minified build for production: -

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

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

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

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 @@ Is this some sort of template language? Specifically no. This might have been th
-
-

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

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

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.

- - - -
-
-