React v0.8

December 19, 2013 by Paul O'Shannessy


I'll start by answering the obvious question:

What happened to 0.6 and 0.7?

It's become increasingly obvious since our launch in May that people want to use React on the server. With the server-side rendering abilities, that's a perfect fit. However using the same copy of React on the server and then packaging it up for the client is surprisingly a harder problem. People have been using our react-tools module which includes React, but when browserifying that ends up packaging all of esprima and some other dependencies that aren't needed on the client. So we wanted to make this whole experience better.

We talked with Jeff Barczewski who was the owner of the react module on npm. He was kind enough to transition ownership to us and release his package under a different name: autoflow. I encourage you to check it out if you're writing a lot of asynchronous code. In order to not break all of react's current users of 0.7.x, we decided to bump our version to 0.8 and skip the issue entirely. We're also including a warning if you use our react module like you would use the previous package.

In order to make the transition to 0.8 for our current users as painless as possible, we decided to make 0.8 primarily a bug fix release on top of 0.5. No public APIs were changed (even if they were already marked as deprecated). We haven't added any of the new features we have in master, though we did take the opportunity to pull in some improvements to internals.

We hope that by releasing react on npm, we will enable a new set of uses that have been otherwise difficult. All feedback is welcome!

Changelog #

React #

  • Added support for more attributes:
    • rows & cols for <textarea>
    • defer & async for <script>
    • loop for <audio> & <video>
    • autoCorrect for form fields (a non-standard attribute only supported by mobile WebKit)
  • Improved error messages
  • Fixed Selection events in IE11
  • Added onContextMenu events

React with Addons #

  • Fixed bugs with TransitionGroup when children were undefined
  • Added support for onTransition

react-tools #

  • Upgraded jstransform and esprima-fb

JSXTransformer #

  • Added support for use in IE8
  • Upgraded browserify, which reduced file size by ~65KB (16KB gzipped)

React v0.5.2, v0.4.2

December 18, 2013 by Paul O'Shannessy


Today we're releasing an update to address a potential XSS vulnerability that can arise when using user data as a key. Typically "safe" data is used for a key, for example, an id from your database, or a unique hash. However there are cases where it may be reasonable to use user generated content. A carefully crafted piece of content could result in arbitrary JS execution. While we make a very concerted effort to ensure all text is escaped before inserting it into the DOM, we missed one case. Immediately following the discovery of this vulnerability, we performed an audit to ensure we this was the only such vulnerability.

This only affects v0.5.x and v0.4.x. Versions in the 0.3.x family are unaffected.

Updated versions are available for immediate download via npm, bower, and on our download page.

We take security very seriously at Facebook. For most of our products, users don't need to know that a security issue has been fixed. But with libraries like React, we need to make sure developers using React have access to fixes to keep their users safe.

While we've encouraged responsible disclosure as part of Facebook's whitehat bounty program since we launched, we don't have a good process for notifying our users. Hopefully we don't need to use it, but moving forward we'll set up a little bit more process to ensure the safety of our users. Ember.js has an excellent policy which we may use as our model.

You can learn more about the vulnerability discussed here: CVE-2013-7035.

Community Round-up #11

November 18, 2013 by Vjeux


This round-up is the proof that React has taken off from its Facebook's root: it features three in-depth presentations of React done by external people. This is awesome, keep them coming!

Super VanJS 2013 Talk #

Steve Luscher working at LeanPub made a 30 min talk at Super VanJS. He does a remarkable job at explaining why React is so fast with very exciting demos using the HTML5 Audio API.

React Tips #

Connor McSheffrey and Cheng Lou added a new section to the documentation. It's a list of small tips that you will probably find useful while working on React. Since each article is very small and focused, we encourage you to contribute!

Intro to the React Framework #

Pavan Podila wrote an in-depth introduction to React on TutsPlus. This is definitively worth reading.

Within a component-tree, data should always flow down. A parent-component should set the props of a child-component to pass any data from the parent to the child. This is termed as the Owner-Owned pair. On the other hand user-events (mouse, keyboard, touches) will always bubble up from the child all the way to the root component, unless handled in between.

Read the full article ...

140-characters textarea #

Brian Kim wrote a small textarea component that gradually turns red as you reach the 140-characters limit. Because he only changes the background color, React is smart enough not to mess with the text selection.

See the Pen FECGb by Brian Kim (@brainkim) on CodePen

Genesis Skeleton #

Eric Clemmons is working on a "Modern, opinionated, full-stack starter kit for rapid, streamlined application development". The version 0.4.0 has just been released and has first-class support for React.

AgFlow Talk #

Robert Zaremba working on AgFlow recently talked in Poland about React.

In a nutshell, I presented why we chose React among other available options (ember.js, angular, backbone ...) in AgFlow, where I’m leading an application development.

During the talk a wanted to highlight that React is not about implementing a Model, but a way to construct visible components with some state. React is simple. It is super simple, you can learn it in 1h. On the other hand what is model? Which functionality it should provide? React does one thing and does it the best (for me)!

Read the full article...

JSX #

Todd Kennedy working at Condé Nast wrote JSXHint and explains in a blog post his perspective on JSX.

Lets start with the elephant in the room: JSX? Is this some sort of template language? Specifically no. This might have been the first big stumbling block. What looks like to be a templating language is actually an in-line DSL that gets transpiled directly into JavaScript by the JSX transpiler.

Creating elements in memory is quick -- copying those elements into the DOM is where the slowness occurs. This is due to a variety of issues, most namely reflow/paint. Changing the items in the DOM causes the browser to re-paint the display, apply styles, etc. We want to keep those operations to an absolute minimum, especially if we're dealing with something that needs to update the DOM frequently.

Read the full article...

Photo Gallery #

Maykel Loomans, designer at Instagram, wrote a gallery for photos he shot using React.

Random Tweet #

Community Round-up #10

November 6, 2013 by Vjeux


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

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

Khan Academy - Officially moving to React #

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

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

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

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

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

Read the full article

React: Rethinking best practices #

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

Server-side React with PHP #

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

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

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

Read part 1 ...

Read part 2 ...

Rendered markup on the server:

TodoMVC Benchmarks #

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

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

Try it yourself!

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

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

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

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

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

Guess the filter #

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

React vs FruitMachine #

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

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

Read the full article...

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

React Brunch #

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

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

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

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

Read more...

Random Tweet #

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

Thinking in React

November 5, 2013 by Pete Hunt


React is, in my opinion, the premier way to build big, fast Web apps with JavaScript. It has scaled very well for us at Facebook and Instagram.

One of the many great parts of React is how it makes you think about apps as you build them. In this post I'll walk you through the thought process of building a searchable product data table using React.

Start with a mock #

Imagine that we already have a JSON API and a mock from our designer. Our designer apparently isn't very good because the mock looks like this:

Mockup

Our JSON API returns some data that looks like this:

[
  {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
  {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
  {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
  {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
  {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
  {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
];

Step 1: break the UI into a component hierarchy #

The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you're working with a designer they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!

But how do you know what should be its own component? Just use the same techniques for deciding if you should create a new function or object. One such technique is the single responsibility principle, that is, a component should ideally only do one thing. If it ends up growing it should be decomposed into smaller subcomponents.

Since you're often displaying a JSON data model to a user, you'll find that if your model was built correctly your UI (and therefore your component structure) will map nicely onto it. That's because user interfaces and data models tend to adhere to the same information architecture which means the work of separating your UI into components is often trivial. Just break it up into components that represent exactly one piece of your data model.

Component diagram

You'll see here that we have five components in our simple app. I've italicized the data each component represents.

  1. FilterableProductTable (orange): contains the entirety of the example
  2. SearchBar (blue): receives all user input
  3. ProductTable (green): displays and filters the data collection based on user input
  4. ProductCategoryRow (turquoise): displays a heading for each category
  5. ProductRow (red): displays a row for each product

If you look at ProductTable you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference and there's an argument to be made either way. For this example I left it as part of ProductTable because it is part of rendering the data collection which is ProductTable's responsibility. However if this header grows to be complex (i.e. if we were to add affordances for sorting) it would certainly make sense to make this its own ProductTableHeader component.

Now that we've identified the components in our mock, let's arrange them into a hierarchy. This is easy. Components that appear within another component in the mock should appear as a child in the hierarchy:

  • FilterableProductTable
    • SearchBar
    • ProductTable
      • ProductCategoryRow
      • ProductRow

Step 2: Build a static version in React #

Now that you have your component hierarchy it's time to start implementing your app. The easiest way is to build a version that takes your data model and renders the UI but has no interactivity. It's easiest to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing. We'll see why.

To build a static version of your app that renders your data model you'll want to build components that reuse other components and pass data using props. props are a way of passing data from parent to child. If you're familiar with the concept of state, don't use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app you don't need it.

You can build top-down or bottom-up. That is, you can either start with building the components higher up in the hierarchy (i.e. starting with FilterableProductTable) or with the ones lower in it (ProductRow). In simpler examples it's usually easier to go top-down and on larger projects it's easier to go bottom-up and write tests as you build.

At the end of this step you'll have a library of reusable components that render your data model. The components will only have render() methods since this is a static version of your app. The component at the top of the hierarchy (FilterableProductTable) will take your data model as a prop. If you make a change to your underlying data model and call renderComponent() again the UI will be updated. It's easy to see how your UI is updated and where to make changes since there's nothing complicated going on since React's one-way data flow (also called one-way binding) keeps everything modular, easy to reason about, and fast.

Simply refer to the React docs if you need help executing this step.

A brief interlude: props vs state #

There are two types of "model" data in React: props and state. It's important to understand the distinction between the two; skim the official React docs if you aren't sure what the difference is.

Step 3: Identify the minimal (but complete) representation of UI state #

To make your UI interactive you need to be able to trigger changes to your underlying data model. React makes this easy with state.

To build your app correctly you first need to think of the minimal set of mutable state that your app needs. The key here is DRY: Don't Repeat Yourself. Figure out what the absolute minimal representation of the state of your application needs to be and compute everything else you need on-demand. For example, if you're building a TODO list, just keep an array of the TODO items around; don't keep a separate state variable for the count. Instead, when you want to render the TODO count simply take the length of the TODO items array.

Think of all of the pieces of data in our example application. We have:

  • The original list of products
  • The search text the user has entered
  • The value of the checkbox
  • The filtered list of products

Let's go through each one and figure out which one is state. Simply ask three questions about each piece of data:

  1. Is it passed in from a parent via props? If so, it probably isn't state.
  2. Does it change over time? If not, it probably isn't state.
  3. Can you compute it based on any other state or props in your component? If so, it's not state.

The original list of products is passed in as props, so that's not state. The search text and the checkbox seem to be state since they change over time and can't be computed from anything. And finally, the filtered list of products isn't state because it can be computed by combining the original list of products with the search text and value of the checkbox.

So finally, our state is:

  • The search text the user has entered
  • The value of the checkbox

Step 4: Identify where your state should live #

OK, so we've identified what the minimal set of app state is. Next we need to identify which component mutates, or owns, this state.

Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. This is often the most challenging part for newcomers to understand, so follow these steps to figure it out:

For each piece of state in your application:

  • Identify every component that renders something based on that state.
  • Find a common owner component (a single component above all the components that need the state in the hierarchy).
  • Either the common owner or another component higher up in the hierarchy should own the state.
  • If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.

Let's run through this strategy for our application:

  • ProductTable needs to filter the product list based on state and SearchBar needs to display the search text and checked state.
  • The common owner component is FilterableProductTable.
  • It conceptually makes sense for the filter text and checked value to live in FilterableProductTable

Cool, so we've decided that our state lives in FilterableProductTable. First, add a getInitialState() method to FilterableProductTable that returns {filterText: '', inStockOnly: false} to reflect the initial state of your application. Then pass filterText and inStockOnly to ProductTable and SearchBar as a prop. Finally, use these props to filter the rows in ProductTable and set the values of the form fields in SearchBar.

You can start seeing how your application will behave: set filterText to "ball" and refresh your app. You'll see the data table is updated correctly.

Step 5: Add inverse data flow #

So far we've built an app that renders correctly as a function of props and state flowing down the hierarchy. Now it's time to support data flowing the other way: the form components deep in the hierarchy need to update the state in FilterableProductTable.

React makes this data flow explicit to make it easy to understand how your program works, but it does require a little more typing than traditional two-way data binding. React provides an add-on called ReactLink to make this pattern as convenient as two-way binding, but for the purpose of this post we'll keep everything explicit.

If you try to type or check the box in the current version of the example you'll see that React ignores your input. This is intentional, as we've set the value prop of the input to always be equal to the state passed in from FilterableProductTable.

Let's think about what we want to happen. We want to make sure that whenever the user changes the form we update the state to reflect the user input. Since components should only update their own state, FilterableProductTable will pass a callback to SearchBar that will fire whenever the state should be updated. We can use the onChange event on the inputs to be notified of it. And the callback passed by FilterableProductTable will call setState() and the app will be updated.

Though this sounds like a lot it's really just a few lines of code. And it's really explicit how your data is flowing throughout the app.

And that's it #

Hopefully this gives you an idea of how to think about building components and applications with React. While it may be a little more typing than you're used to, remember that code is read far more than it's written, and it's extremely easy to read this modular, explicit code. As you start to build large libraries of components you'll appreciate this explicitness and modularity, and with code reuse your lines of code will start to shrink :)