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 #

React v0.11.1

July 25, 2014 by Paul O’Shannessy


Today we're releasing React v0.11.1 to address a few small issues. Thanks to everybody who has reported them as they've begun upgrading.

The first of these is the most major and resulted in a regression with the use of setState inside componentWillMount when using React on the server. These setState calls are batched into the initial render. A change we made to our batching code resulted in this path hitting DOM specific code when run server-side, in turn throwing an error as document is not defined.

There are several fixes we're including in v0.11.1 that are focused around the newly supported event.getModifierState() function. We made some adjustments to improve this cross-browser standardization.

The final fix we're including is to better support a workaround for some IE8 behavior. The edge-case bug we're fixing was also present in v0.9 and v0.10, so while it wasn't a short-term regression, we wanted to make sure we support IE8 to the best of our abilities.

We'd also like to call out a couple additional breaking changes that we failed to originally mention in the release notes for v0.11. We updated that blog post and the changelog, so we encourage you to go read about the changes around Descriptors and Prop Type Validation.

The release is available for download from the CDN:

We've also published version 0.11.1 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.

Changelog #

React Core #

Bug Fixes #

  • setState can be called inside componentWillMount in non-DOM environments
  • SyntheticMouseEvent.getEventModifierState correctly renamed to getModifierState
  • getModifierState correctly returns a boolean
  • getModifierState is now correctly case sensitive
  • Empty Text node used in IE8 innerHTML workaround is now removed, fixing rerendering in certain cases

JSXTransformer #

  • Fix duplicate variable declaration (caused issues in some browsers)