React v0.14 Release Candidate

September 10, 2015 by Ben Alpert


We’re happy to announce our first release candidate for React 0.14! We gave you a sneak peek in July at the upcoming changes but we’ve now stabilized the release more and we’d love for you to try it out before we release the final version.

Let us know if you run into any problems by filing issues on our GitHub repo.

Installation

We recommend using React from npm and using a tool like browserify or webpack to build your code into a single package:

Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, set the NODE_ENV environment variable to production to use the production build of React which does not include the development warnings and runs significantly faster.

If you can’t use npm yet, we also provide pre-built browser builds for your convenience:

These builds are also available in the react package on bower.

Changelog

Major changes

  • Two Packages: React and React DOM

    As we look at packages like react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.

    To make this more clear and to make it easier to build more environments that React can render to, we’re splitting the main react package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native. We don’t expect all the code in an app to be shared, but we want to be able to share the components that do behave the same across platforms.

    The react package contains React.createElement, .createClass, .Component, .PropTypes, .Children, and the other helpers related to elements and component classes. We think of these as the isomorphic or universal helpers that you need to build components.

    The react-dom package has ReactDOM.render, .unmountComponentAtNode, and .findDOMNode. In react-dom/server we have server-side rendering support with ReactDOMServer.renderToString and .renderToStaticMarkup.

    var React = require('react');
    var ReactDOM = require('react-dom');
    
    var MyComponent = React.createClass({
      render: function() {
        return <div>Hello World</div>;
      }
    });
    
    ReactDOM.render(<MyComponent />, node);
    

    We’ve published the automated codemod script we used at Facebook to help you with this transition.

    The add-ons have moved to separate packages as well: react-addons-clone-with-props, react-addons-create-fragment, react-addons-css-transition-group, react-addons-linked-state-mixin, react-addons-perf, react-addons-pure-render-mixin, react-addons-shallow-compare, react-addons-test-utils, react-addons-transition-group, and react-addons-update, plus ReactDOM.unstable_batchedUpdates in react-dom.

    For now, please use matching versions of react and react-dom in your apps to avoid versioning problems.

  • DOM node refs

    The other big change we’re making in this release is exposing refs to DOM components as the DOM node itself. That means: we looked at what you can do with a ref to a React DOM component and realized that the only useful thing you can do with it is call this.refs.giraffe.getDOMNode() to get the underlying DOM node. In this release, this.refs.giraffe is the actual DOM node. Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.

    var Zoo = React.createClass({
      render: function() {
        return <div>Giraffe name: <input ref="giraffe" /></div>;
      },
      showName: function() {
        // Previously: var input = this.refs.giraffe.getDOMNode();
        var input = this.refs.giraffe;
        alert(input.value);
      }
    });
    

    This change also applies to the return result of ReactDOM.render when passing a DOM node as the top component. As with refs, this change does not affect custom components. With these changes, we’re deprecating .getDOMNode() and replacing it with ReactDOM.findDOMNode (see below).

  • Stateless function components

    In idiomatic React code, most of the components you write will be stateless, simply composing other components. We’re introducing a new, simpler syntax for these components where you can take props as an argument and return the element you want to render:

    // Using an ES2015 (ES6) arrow function:
    var Aquarium = (props) => {
      var fish = getFish(props.species);
      return <Tank>{fish}</Tank>;
    };
    
    // Or with destructuring and an implicit return, simply:
    var Aquarium = ({species}) => (
      <Tank>
        {getFish(species)}
      </Tank>
    );
    
    // Then use: <Aquarium species="rainbowfish" />
    

    This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.

  • Deprecation of react-tools

    The react-tools package and JSXTransformer.js browser file have been deprecated. You can continue using version 0.13.3 of both, but we no longer support them and recommend migrating to Babel, which has built-in support for React and JSX.

  • Compiler optimizations

    React now supports two compiler optimizations that can be enabled in Babel 5.8.23 and newer. Both of these transforms should be enabled only in production (e.g., just before minifying your code) because although they improve runtime performance, they make warning messages more cryptic and skip important checks that happen in development mode, including propTypes.

    Inlining React elements: The optimisation.react.inlineElements transform converts JSX elements to object literals like {type: 'div', props: ...} instead of calls to React.createElement.

    Constant hoisting for React elements: The optimisation.react.constantElements transform hoists element creation to the top level for subtrees that are fully static, which reduces calls to React.createElement and the resulting allocations. More importantly, it tells React that the subtree hasn’t changed so React can completely skip it when reconciling.

Breaking changes

As always, we have a few breaking changes in this release. Whenever we make large changes, we warn for at least one release so you have time to update your code. The Facebook codebase has over 15,000 React components, so on the React team, we always try to minimize the pain of breaking changes.

These three breaking changes had a warning in 0.13, so you shouldn’t have to do anything if your code is already free of warnings:

  • The props object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, React.cloneElement should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.
  • Plain objects are no longer supported as React children; arrays should be used instead. You can use the createFragment helper to migrate, which now returns an array.
  • Add-Ons: classSet has been removed. Use classnames instead.

And these two changes did not warn in 0.13 but should be easy to find and clean up:

  • React.initializeTouchEvents is no longer necessary and has been removed completely. Touch events now work automatically.
  • Add-Ons: Due to the DOM node refs change mentioned above, TestUtils.findAllInRenderedTree and related helpers are no longer able to take a DOM component, only a custom component.

New deprecations, introduced with a warning

  • Due to the DOM node refs change mentioned above, this.getDOMNode() is now deprecated and ReactDOM.findDOMNode(this) can be used instead. Note that in most cases, calling findDOMNode is now unnecessary – see the example above in the “DOM node refs” section.

    If you have a large codebase, you can use our automated codemod script to change your code automatically.

  • setProps and replaceProps are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.

  • ES6 component classes must now extend React.Component in order to enable stateless function components. The ES3 module pattern will continue to work.

  • Reusing and mutating a style object between renders has been deprecated. This mirrors our change to freeze the props object.

  • Add-Ons: cloneWithProps is now deprecated. Use React.cloneElement instead (unlike cloneWithProps, cloneElement does not merge className or style automatically; you can merge them manually if needed).

  • Add-Ons: To improve reliability, CSSTransitionGroup will no longer listen to transition events. Instead, you should specify transition durations manually using props such as transitionEnterTimeout={500}.

Notable enhancements

  • Added React.Children.toArray which takes a nested children object and returns a flat array with keys assigned to each child. This helper makes it easier to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down. In addition, React.Children.map now returns plain arrays too.
  • React uses console.error instead of console.warn for warnings so that browsers show a full stack trace in the console. (Our warnings appear when you use patterns that will break in future releases and for code that is likely to behave unexpectedly, so we do consider our warnings to be “must-fix” errors.)
  • Previously, including untrusted objects as React children could result in an XSS security vulnerability. This problem should be avoided by properly validating input at the application layer and by never passing untrusted objects around your application code. As an additional layer of protection, React now tags elements with a specific ES2015 (ES6) Symbol in browsers that support it, in order to ensure that React never considers untrusted JSON to be a valid element. If this extra security protection is important to you, you should add a Symbol polyfill for older browsers, such as the one included by Babel’s polyfill.
  • When possible, React DOM now generates XHTML-compatible markup.
  • React DOM now supports these standard HTML attributes: capture, challenge, inputMode, is, keyParams, keyType, minLength, summary, wrap. It also now supports these non-standard attributes: autoSave, results, security.
  • React DOM now supports these SVG attributes, which render into namespaced attributes: xlinkActuate, xlinkArcrole, xlinkHref, xlinkRole, xlinkShow, xlinkTitle, xlinkType, xmlBase, xmlLang, xmlSpace.
  • The image SVG tag is now supported by React DOM.
  • In React DOM, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an is="..." attribute).
  • React DOM now supports these media events on audio and video tags: onAbort, onCanPlay, onCanPlayThrough, onDurationChange, onEmptied, onEncrypted, onEnded, onError, onLoadedData, onLoadedMetadata, onLoadStart, onPause, onPlay, onPlaying, onProgress, onRateChange, onSeeked, onSeeking, onStalled, onSuspend, onTimeUpdate, onVolumeChange, onWaiting.
  • Many small performance improvements have been made.
  • Many warnings show more context than before.
  • Add-Ons: A shallowCompare add-on has been added as a migration path for PureRenderMixin in ES6 classes.
  • Add-Ons: CSSTransitionGroup can now use custom class names instead of appending -enter-active or similar to the transition name.

New helpful warnings

  • React DOM now warns you when nesting HTML elements invalidly, which helps you avoid surprising errors during updates.
  • Passing document.body directly as the container to ReactDOM.render now gives a warning as doing so can cause problems with browser extensions that modify the DOM.
  • Using multiple instances of React together is not supported, so we now warn when we detect this case to help you avoid running into the resulting problems.

Notable bug fixes

  • Click events are handled by React DOM more reliably in mobile browsers, particularly in Mobile Safari.
  • SVG elements are created with the correct namespace in more cases.
  • React DOM now renders <option> elements with multiple text children properly and renders <select> elements on the server with the correct option selected.
  • When two separate copies of React add nodes to the same document (including when a browser extension uses React), React DOM tries harder not to throw exceptions during event handling.
  • Using non-lowercase HTML tag names in React DOM (e.g., React.createElement('DIV')) no longer causes problems, though we continue to recommend lowercase for consistency with the JSX tag name convention (lowercase names refer to built-in components, capitalized names refer to custom components).
  • React DOM understands that these CSS properties are unitless and does not append “px” to their values: animationIterationCount, boxOrdinalGroup, flexOrder, tabSize, stopOpacity.
  • Add-Ons: When using the test utils, Simulate.mouseEnter and Simulate.mouseLeave now work.
  • Add-Ons: ReactTransitionGroup now correctly handles multiple nodes being removed simultaneously.

New React Developer Tools

September 2, 2015 by Ben Alpert


A month ago, we posted a beta of the new React developer tools. Today, we're releasing the first stable version of the new devtools. We're calling it version 0.14, but it's a full rewrite so we think of it more like a 2.0 release.

Video/screenshot of new devtools

It contains a handful of new features, including:

  • Built entirely with React, making it easier to develop and extend
  • Firefox support
  • Selected component instance is available as $r from the console
  • More detail is shown in props in the component tree
  • Right-click any node and choose "Show Source" to jump to the render method in the Sources panel
  • Right-click any props or state value to make it available as $tmp from the console
  • Full React Native support

Installation

Download the new devtools from the Chrome Web Store and on Mozilla Add-ons for Firefox. If you're developing using React, we highly recommend installing these devtools.

If you already have the Chrome extension installed, it should autoupdate within the next week. You can also head to chrome://extensions and click "Update extensions now" if you'd like to get the new version today. If you installed the devtools beta, please remove it and switch back to the version from the store to make sure you always get the latest updates and bug fixes.

If you run into any issues, please post them on our react-devtools GitHub repo.

ReactEurope Round-up

August 13, 2015 by Matthew Johnston


Last month, the first React.js European conference took place in the city of Paris, at ReactEurope. Attendees were treated to a range of talks covering React, React Native, Flux, Relay, and GraphQL. Big thanks to everyone involved with organizing the conference, to all the attendees, and everyone who gave their time to speak - it wouldn't have been possible without the help and support of the React community.

Christopher Chedeau gave the opening keynote to the conference:

Spencer Ahrens walks through building an advanced gestural UI leveraging the unique power of the React Native layout and animation systems to build a complex and fluid experience:

Lee Byron explores GraphQL, its core principles, how it works, and what makes it a powerful tool:

Joseph Savona explores the problems Relay solves, its architecture and the query lifecycle, and how can you use Relay to build more scalable apps. There are examples of how Relay powers applications as complex as the Facebook News Feed:

Nick Schrock and Dan Schafer take a deeper dive into putting GraphQL to work. How can we build a GraphQL API to work with an existing REST API or server-side data model? What are best practices when building a GraphQL API, and how do they differ from traditional REST best practices? How does Facebook use GraphQL? Most importantly, what does a complete and coherent GraphQL API looks like, and how can we get started building one?

Sebastian Markbåge talks about why the DOM is flawed and how it is becoming a second-class citizen in the land of React apps:

Sebastian McKenzie goes over how existing JSX build pipeline infrastructure can be further utilised to perform even more significant code transformations such as transpilation, optimisation, profiling and more, reducing bugs, making your code faster and you as a developer more productive and happy:

Cheng Lou gives a talk on the past, the present and the future of animation, and the place React can potentially take in this:

And there was a Q&A session with the whole team covering a range of React topics:

And there were lots of great talks from the React community:

  • Michael Chan looks at how to solve problems like CSS theming and media queries with contexts and plain old JavaScript. He also looks at the role of container-components and when it's better to "just use CSS.".
  • Elie Rotenberg talks about Flux over the Wire, building isomorphic, real-time React apps using a novel interpretation of Flux.
  • Ryan Florence says “Your front and back ends are already successfully in production but you don't have to miss out on the productivity that React brings. Forget the rewrites, this is brownfield!”.
  • Dan Abramov demonstrates how React can be used together with Webpack Hot Module Replacement to create a live editing environment with time travel that supercharges your debugging experience and transforms the way you work on real apps every day.
  • Mikhail Davydov shows you how to ask the browser layout engine for help, how to avoid slavery of DSL, and build declarative Text UI using only web-technologies like HTML, JS, CSS and React.
  • Kevin Robinson shares how user experience choices are a primary influence on how Twitter design the data layer, especially for teams developing new products with full-stack capabilities.
  • Jed Watson shares what Thinkmill have learned about React and mobile app development, and how they've approached the unique challenges of mobile web apps - with tools that are useful to all developers building touch interfaces with React, as well as a walkthrough of their development process and framework.
  • Michael Jackson discusses how your users can benefit from the many tools that React Router provides including server-side rendering, real URLs on native devices, and much, much more.
  • Michael Ridgway walks you through an isomorphic Flux architecture to give you the holy grail of frontend development.
  • Aria Buckles covers Khan Academy's techniques and patterns to make dealing with large pure components simpler, as well as current open questions.
  • Evan Morikawa and Ben Gotow talk about specific features of React & Flux, React CSS, programming design patterns, and custom libraries, which can turn a static application into a dynamic platform that an ecosystem of developers can build on top of.
  • Zalando, Rangle.io, Automattic, Thinkmill, and Red Badger provided lots of insight into how larger companies are using React.

There was also a great series of Lightning talks from Joshua Sierles, Ovidiu Cherecheș, Mike Grabowski, Dave Brotherstone, Sunil Pai, Andreas Savvides, and Petr Bela.

You can view the full list of talks on the ReactEurope YouTube channel.

Relay Technical Preview

August 11, 2015 by Joseph Savona


Relay

Today we're excited to share an update on Relay - the technical preview is now open-source and available on GitHub.

Why Relay

While React simplified the process of developing complex user-interfaces, it left open the question of how to interact with data on the server. It turns out that this was a significant source of friction for our developers; fragile coupling between client and server caused data-related bugs and made iteration harder. Furthermore, developers were forced to constantly re-implement complex async logic instead of focusing on their apps. Relay addresses these concerns by borrowing important lessons from React: it provides declarative, component-oriented data fetching for React applications.

Declarative data-fetching means that Relay applications specify what data they need, not how to fetch that data. Just as React uses a description of the desired UI to manage view updates, Relay uses a data description in the form of GraphQL queries. Given these descriptions, Relay coalesces queries into batches for efficiency, manages error-prone asynchronous logic, caches data for performance, and automatically updates views as data changes.

Relay is also component-oriented, extending the notion of a React component to include a description of what data is necessary to render it. This colocation allows developers to reason locally about their application and eliminates bugs such as under- or over-fetching data.

Relay is in use at Facebook in production apps, and we're using it more and more because Relay lets developers focus on their products and move fast. It's working for us and we'd like to share it with the community.

What's Included

We're open-sourcing a technical preview of Relay - the core framework that we use internally, with some modifications for use outside Facebook. As this is the first release, it's good to keep in mind that there may be some incomplete or missing features. We'll continue to develop Relay and are working closely with the GraphQL community to ensure that Relay tracks updates during GraphQL's RFC period. But we couldn't wait any longer to get this in your hands, and we're looking forward to your feedback and contributions.

Relay is available on GitHub and npm.

What's Next

The team is super excited to be releasing Relay - and just as excited about what's next. Here are some of the things we'll be focusing on:

  • Offline support. This will allow applications to fulfill queries and enqueue updates without connectivity.
  • Real-time updates. In collaboration with the GraphQL community, we're working to define a specification for subscriptions and provide support for them in Relay.
  • A generic Relay. Just as the power of React was never about the virtual DOM, Relay is much more than a GraphQL client. We're working to extend Relay to provide a unified interface for interacting not only with server data, but also in-memory and native device data (and, even better, a mix of all three).
  • Finally, it's all too easy as developers to focus on those people with the newest devices and fastest internet connections. We're working to make it easier to build applications that are robust in the face of slow or intermittent connectivity.

Thanks!

New React Devtools Beta

August 3, 2015 by Jared Forsyth


We've made an entirely new version of the devtools, and we want you to try it out!

The full devtools gif

Why entirely new?

Perhaps the biggest reason was to create a defined API for dealing with internals, so that other tools could benefit as well and not have to depend on implementation details. This gives us more freedom to refactor things internally without worrying about breaking tooling.

The current version of the devtools is a fork of Blink's "Elements" pane, and is imperative, mutation-driven, and tightly integrated with Chrome-specific APIs. The new devtools are much less coupled to Chrome, and easier to reason about thanks to React.

What are the benefits?

  • 100% React
  • Firefox compatible
  • React Native compatible
  • more extensible & hackable

Are there any new features?

Yeah!

The Tree View

The new tree view of the devtools

  • Much richer view of your props, including the contents of objects and arrays
  • Custom components are emphasized, native components are de-emphasized
  • Stateful components have a red collapser
  • Improved keyboard navigation (hjkl or arrow keys)
  • Selected component is available in the console as $r
  • Props that change highlight in green
  • Right-click menu

    • Scroll node into view
    • Show the source for a component in the "Sources" pane
    • Show the element in the "Elements" pane

Searching

Select the search bar (or press "/"), and start searching for a component by name.

The Side Pane

  • Now shows the context for a component
  • Right-click to store a prop/state value as a global variable

How do I install it?

First, disable the Chrome web store version, or it will break things. Then download the .crx and drag it into your chrome://extensions page. If it's not working to drag it from the downloads bar, try opening your downloads folder and drag it from there.

Once we've determined that there aren't any major regressions, we'll update the official web store version, and everyone will be automatically upgraded.

Also Firefox!

We also have an initial version of the devtools for Firefox, which you can download from the same release page.

Feedback welcome

Let us know what issues you run into on GitHub, and check out the README for more info.

Update

August 12, 2015

A second beta is out, with a number of bugfixes. It is also listed on the releases page.