Community Round-up #22

September 12, 2014 by Lou Husson


This has been an exciting summer as four big companies: Yahoo, Mozilla, Airbnb and Reddit announced that they were using React!

React's Architecture

Vjeux, from the React team, gave a talk at OSCON on the history of React and the various optimizations strategies that are implemented. You can also check out the annotated slides or Chris Dawson's notes titled JavaScript’s History and How it Led To React.

v8 optimizations

Jakob Kummerow landed two optimizations to V8 specifically targeted at optimizing React. That's really exciting to see browser vendors helping out on performance!

Reusable Components by Khan Academy

Khan Academy released many high quality standalone components they are using. This is a good opportunity to see what React code used in production look like.

var TeX = require('react-components/js/tex.jsx');
React.renderComponent(<TeX>\nabla \cdot E = 4 \pi \rho</TeX>, domNode);

var translated = (
  <$_ first="Motoko" last="Kusanagi">
    Hello, %(first)s %(last)s!
  </$_>
);

React + Browserify + Gulp

Trường wrote a little guide to help your getting started using React, Browserify and Gulp.

React Style

After React put HTML inside of JavaScript, Sander Spies takes the same approach with CSS: IntegratedCSS. It seems weird at first but this is the direction where React is heading.

var Button = React.createClass({
  normalStyle: ReactStyle(function() {
    return { backgroundColor: vars.orange };
  }),
  activeStyle: ReactStyle(function() {
    if (this.state.active) {
      return { color: 'yellow', padding: '10px' };
    }
  }),
  render: function() {
    return (
      <div styles={[this.normalStyle(), this.activeStyle()]}>
        Hello, I'm styled
      </div>
    );
  }
});

Virtual DOM in Elm

Evan Czaplicki explains how Elm implements the idea of a Virtual DOM and a diffing algorithm. This is great to see React ideas spread to other languages.

Performance is a good hook, but the real benefit is that this approach leads to code that is easier to understand and maintain. In short, it becomes very simple to create reusable HTML widgets and abstract out common patterns. This is why people with larger code bases should be interested in virtual DOM approaches.

Read the full article

Components Tutorial

If you are getting started with React, Joe Maddalone made a good tutorial on how to build your first component.

Saving time & staying sane?

When Kent William Innholt who works at M>Path summed up his experience using React in an article.

We're building an ambitious new web app, where the UI complexity represents most of the app's complexity overall. It includes a tremendous amount of UI widgets as well as a lot rules on what-to-show-when. This is exactly the sort of situation React.js was built to simplify.

  • Big win: Tighter coupling of markup and behavior
  • Jury's still out: CSS lives outside React.js
  • Big win: Cascading updates and functional thinking
  • Jury's still out: Verbose propagation

Read the article...

Weather

To finish this round-up, Andrew Gleave made a page that displays the Weather. It's great to see that React is also used for small prototypes.

Introducing the JSX Specification

September 3, 2014 by Sebastian Markbåge


At Facebook we've been using JSX for a long time. We originally introduced it to the world last year alongside React, but we actually used it in another form before that to create native DOM nodes. We've also seen some similar efforts grow out of our work in order to be used with other libraries and in interesting ways. At this point React JSX is just one of many implementations.

In order to make it easier to implement new versions and to make sure that the syntax remains compatible, we're now formalizing the syntax of JSX in a stand-alone spec without any semantic meaning. It's completely stand-alone from React itself.

Read the spec now at https://facebook.github.io/jsx/.

This is not a proposal to be standardized in ECMAScript. It's just a reference document that transpiler writers and syntax highlighters can agree on. It's currently in a draft stage and will probably continue to be a living document.

Feel free to open an Issue or Pull Request if you find something wrong.

Community Round-up #21

August 3, 2014 by Lou Husson


React Router

Ryan Florence and Michael Jackson ported Ember's router to React in a project called React Router. This is a very good example of both communities working together to make the web better!

React.renderComponent((
  <Routes>
    <Route handler={App}>
      <Route name="about" handler={About}/>
      <Route name="users" handler={Users}>
        <Route name="user" path="/user/:userId" handler={User}/>
      </Route>
    </Route>
  </Routes>
), document.getElementById('example'));

Going Big with React

Areeb Malik, from Facebook, talks about his experience using React. "On paper, all those JS frameworks look promising: clean implementations, quick code design, flawless execution. But what happens when you stress test Javascript? What happens when you throw 6 megabytes of code at it? In this talk, we'll investigate how React performs in a high stress situation, and how it has helped our team build safe code on a massive scale"

What is React?

Craig McKeachie author of Javascript Framework Guide wrote an excellent news named "What is React.js? Another Template Library?

  • Is React a template library?
  • Is React similar to Web Components?
  • Are the Virtual DOM and Shadow DOM the same?
  • Can React be used with other JavaScript MVC frameworks?
  • Who uses React?
  • Is React a premature optimization if you aren’t Facebook or Instagram?
  • Can I work with designers?
  • Will React hurt my search engine optimizations (SEO)?
  • Is React a framework for building applications or a library with one feature?
  • Are components a better way to build an application?
  • Can I build something complex with React?

Referencing Dynamic Children

While Matt Zabriskie was working on react-tabs he discovered how to use React.Children.map and React.addons.cloneWithProps in order to reference dynamic children.

var App = React.createClass({
  render: function () {
    var children = React.Children.map(this.props.children, function(child, index) {
      return React.addons.cloneWithProps(child, {
        ref: 'child-' + index
      });
    });
    return <div>{children}</div>;
  }
});

JSX with Sweet.js using Readtables

Have you ever wondered how JSX was implemented? James Long wrote a very instructive blog post that explains how to compile JSX with Sweet.js using Readtables.

First Look: Getting Started with React

Kirill Buga wrote an article on Modern Web explaining how React is different from traditional MVC used by most JavaScript applications

React Draggable

Matt Zabriskie released a project to make your react components draggable.

HTML Parser2 React

Jason Brown adapted htmlparser2 to React: htmlparser2-react. That allows you to convert raw HTML to the virtual DOM. This is not the intended way to use React but can be useful as last resort if you have an existing piece of HTML.

var html = '<div data-id="1" class="hey this is a class" ' +
  'style="width:100%;height: 100%;"><article id="this-article">' +
  '<p>hey this is a paragraph</p><div><ul><li>1</li><li>2</li>' +
  '<li>3</li></ul></div></article></div>';
var parsedComponent = reactParser(html, React);

Building UIs with React

If you haven't yet tried out React, Jacob Rios did a Hangout where he covers the most important aspects and thankfully he recorded it!

Random Tweets

Flux: Actions and the Dispatcher

July 30, 2014 by Bill Fisher


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

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

Where the Dispatcher Fits in the Flux Data Flow

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

Actions and ActionCreators

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

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

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

Why We Need a Dispatcher

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

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

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

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

Example Chat App

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

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

Community Round-up #20

July 28, 2014 by Lou Husson


It's an exciting time for React as there are now more commits from open source contributors than from Facebook engineers! Keep up the good work :)

Atom moves to React

Atom, GitHub's code editor, is now using React to build the editing experience. They made the move in order to improve performance. By default, React helped them eliminate unnecessary reflows, enabling them to focus on architecting the rendering pipeline in order to minimize repaints by using hardware acceleration. This is a testament to the fact that React's architecture is perfect for high performant applications.

Why Does React Scale?

At the last JSConf.us, Vjeux talked about the design decisions made in the API that allows it to scale to a large number of developers. If you don't have 20 minutes, take a look at the annotated slides.

Live Editing

One of the best features of React is that it provides the foundations to implement concepts that were otherwise extremely difficult, like server-side rendering, undo-redo, rendering to non-DOM environments like canvas... Dan Abramov got hot code reloading working with webpack in order to live edit a React project!

ReactIntl Mixin by Yahoo

There are a couple of React-related projects that recently appeared on Yahoo's GitHub, the first one being an internationalization mixin. It's great to see them getting excited about React and contributing back to the community.

var MyComponent = React.createClass({
  mixins: [ReactIntlMixin],
  render: function() {
    return (
      <div>
        <p>{this.intlDate(1390518044403, { hour: 'numeric', minute: 'numeric' })}</p>
        <p>{this.intlNumber(400, { style: 'percent' })}</p>
      </div>
    );
  }
});

React.renderComponent(
  <MyComponent locales={['fr-FR']} />,
  document.getElementById('example')
);

Thinking and Learning React

Josephine Hall, working at Icelab, used React to write a mobile-focused application. She wrote a blog post “Thinking and Learning React.js” to share her experience with elements they had to use. You'll learn about routing, event dispatch, touchable components, and basic animations.

London React Meetup

If you missed the last London React Meetup, the video is available, with lots of great content.

  • What's new in React 0.11 and how to improve performance by guaranteeing immutability
  • State handling in React with Morearty.JS
  • React on Rails - How to use React with Ruby on Rails to build isomorphic apps
  • Building an isomorphic, real-time to-do list with moped and node.js

In related news, the next React SF Meetup will be from Prezi: “Immediate Mode on the Web: How We Implemented the Prezi Viewer in JavaScript”. While not in React, their tech is really awesome and shares a lot of React's design principles and perf optimizations.

Using React and KendoUI Together

One of the strengths of React is that it plays nicely with other libraries. Jim Cowart proved it by writing a tutorial that explains how to write React component adapters for KendoUI.

Acorn JSX

Ingvar Stepanyan extended the Acorn JavaScript parser to support JSX. The result is a JSX parser that's 1.5–2.0x faster than the official JSX implementation. It is an experiment and is not meant to be used for serious things, but it's always a good thing to get competition on performance!

ReactScriptLoader

Yariv Sadan created ReactScriptLoader to make it easier to write components that require an external script.

var Foo = React.createClass({
  mixins: [ReactScriptLoaderMixin],
  getScriptURL: function() {
    return 'http://d3js.org/d3.v3.min.js';
  },
  getInitialState: function() {
    return { scriptLoading: true, scriptLoadError: false };
  },
  onScriptLoaded: function() {
    this.setState({scriptLoading: false});
  },
  onScriptError: function() {
    this.setState({scriptLoading: false, scriptLoadError: true});
  },
  render: function() {
    var message =
      this.state.scriptLoading ? 'Loading script...' :
      this.state.scriptLoadError ? 'Loading failed' :
      'Loading succeeded';
    return <span>{message}</span>;
  }
});

Random Tweet