Use React and JSX in Ruby on Rails

July 30, 2013 by Paul O’Shannessy


Today we're releasing a gem to make it easier to use React and JSX in Ruby on Rails applications: react-rails.

This gem has 2 primary purposes:

  1. To package react.js in a way that's easy to use and easy to update.
  2. To allow you to write JSX without an external build step to transform that into JS.

Packaging react.js #

To make react.js available for use client-side, simply add react to your manifest, and declare the variant you'd like to use in your environment. When you use :production, the minified and optimized react.min.js will be used instead of the development version. For example:

# config/environments/development.rb

MyApp::Application.configure do
  config.react.variant = :development
  # use :production in production.rb
end
// app/assets/javascript/application.js

//= require react

Writing JSX #

When you name your file with myfile.js.jsx, react-rails will automatically try to transform that file. For the time being, we still require that you include the docblock at the beginning of the file. For example, this file will get transformed on request.

/** @jsx React.DOM */
React.renderComponent(<MyComponent/>, document.getElementById('example'))

Asset Pipeline #

react-rails takes advantage of the asset pipeline that was introduced in Rails 3.1. A very important part of that pipeline is the assets:precompile Rake task. react-rails will ensure that your JSX files will be transformed into regular JS before all of your assets are minified and packaged.

Installation #

Installation follows the same process you're familiar with. You can install it globally with gem install react-rails, though we suggest you add the dependency to your Gemfile directly.

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


We launched the React Facebook Page along with the React v0.4 launch. 700 people already liked it to get updated on the project :)

Cross-browser onChange #

Ben Alpert from Khan Academy worked on a cross-browser implementation of onChange event that landed in v0.4. He wrote a blog post explaining the various browser quirks he had to deal with.

First off, what is the input event? If you have an <input> element and want to receive events whenever the value changes, the most obvious thing to do is to listen to the change event. Unfortunately, change fires only after the text field is defocused, rather than on each keystroke. The next obvious choice is the keyup event, which is triggered whenever a key is released. Unfortunately, keyup doesn't catch input that doesn't involve the keyboard (e.g., pasting from the clipboard using the mouse) and only fires once if a key is held down, rather than once per inserted character.

Both keydown and keypress do fire repeatedly when a key is held down, but both fire immediately before the value changes, so to read the new value you have to defer the handler to the next event loop using setTimeout(fn, 0) or similar, which slows down your app. Of course, like keyup, neither keydown nor keypress fires for non-keyboard input events, and all three can fire in cases where the value doesn't change at all (such as when pressing the arrow keys).

Read the full post...

React Samples #

Learning a new library is always easier when you have working examples you can play with. jwh put many of them on his react-samples Github repo.

Some simple examples with Facebook's React framework

React Chosen Wrapper #

Cheng Lou wrote a wrapper for the Chosen input library called react-chosen. It took just 25 lines to be able to use jQuery component as a React one.

React.renderComponent(
  <Chosen noResultsText="No result" value="Harvest" onChange={doSomething}>
    <option value="Facebook">Facebook</option>
    <option value="Harvest">Harvest</option>
  </Chosen>
, document.getElementById('example'));

JSX and ES6 Template Strings #

Domenic Denicola wrote a slide deck about the great applications of ES6 features and one slide shows how we could use Template Strings to compile JSX at run-time without the need for a pre-processing phase.

React Presentation #

Tom Occhino and Jordan Walke, React developers, did a presentation of React at Facebook Seattle's office. Check out the first 25 minutes for the presentation and the remaining 45 for a Q&A. I highly recommend you watching this video.

Docs #

Pete Hunt rewrote the entirety of the docs for v0.4. The goal was to add more explanation about why we built React and what the best practices are.

Guides

React v0.4.0

July 17, 2013 by Paul O’Shannessy


Over the past 2 months we've been taking feedback and working hard to make React even better. We fixed some bugs, made some under-the-hood improvements, and added several features that we think will improve the experience developing with React. Today we're proud to announce the availability of React v0.4!

This release could not have happened without the support of our growing community. Since launch day, the community has contributed blog posts, questions to the Google Group, and issues and pull requests on GitHub. We've had contributions ranging from documentation improvements to major changes to React's rendering. We've seen people integrate React into the tools they're using and the products they're building, and we're all very excited to see what our budding community builds next!

React v0.4 has some big changes. We've also restructured the documentation to better communicate how to use React. We've summarized the changes below and linked to documentation where we think it will be especially useful.

When you're ready, go download it!

React #

  • Switch from using id attribute to data-reactid to track DOM nodes. This allows you to integrate with other JS and CSS libraries more easily.
  • Support for more DOM elements and attributes (e.g., <canvas>)
  • Improved server-side rendering APIs. React.renderComponentToString(<component>, callback) allows you to use React on the server and generate markup which can be sent down to the browser.
  • prop improvements: validation and default values. Read our blog post for details...
  • Support for the key prop, which allows for finer control over reconciliation. Read the docs for details...
  • Removed React.autoBind. Read our blog post for details...
  • Improvements to forms. We've written wrappers around <input>, <textarea>, <option>, and <select> in order to standardize many inconsistencies in browser implementations. This includes support for defaultValue, and improved implementation of the onChange event, and circuit completion. Read the docs for details...
  • We've implemented an improved synthetic event system that conforms to the W3C spec.
  • Updates to your component are batched now, which may result in a significantly faster re-render of components. this.setState now takes an optional callback as its second parameter. If you were using onClick={this.setState.bind(this, state)} previously, you'll want to make sure you add a third parameter so that the event is not treated as the callback.

JSX #

  • Support for comment nodes <div>{/* this is a comment and won't be rendered */}</div>
  • Children are now transformed directly into arguments instead of being wrapped in an array E.g. <div><Component1/><Component2/></div> is transformed into React.DOM.div(null, Component1(null), Component2(null)). Previously this would be transformed into React.DOM.div(null, [Component1(null), Component2(null)]). If you were using React without JSX previously, your code should still work.

react-tools #

  • Fixed a number of bugs when transforming directories
  • No longer re-write require()s to be relative unless specified

New in React v0.4: Prop Validation and Default Values

July 11, 2013 by Paul O’Shannessy


Many of the questions we got following the public launch of React revolved around props, specifically that people wanted to do validation and to make sure their components had sensible defaults.

Validation #

Oftentimes you want to validate your props before you use them. Perhaps you want to ensure they are a specific type. Or maybe you want to restrict your prop to specific values. Or maybe you want to make a specific prop required. This was always possible — you could have written validations in your render or componentWillReceiveProps functions, but that gets clunky fast.

React v0.4 will provide a nice easy way for you to use built-in validators, or to even write your own.

React.createClass({
  propTypes: {
    // An optional string prop named "description".
    description: React.PropTypes.string,

    // A required enum prop named "category".
    category: React.PropTypes.oneOf(['News','Photos']).isRequired,

    // A prop named "dialog" that requires an instance of Dialog.
    dialog: React.PropTypes.instanceOf(Dialog).isRequired
  },
  ...
});

Default Values #

One common pattern we've seen with our React code is to do something like this:

React.createClass({
  render: function() {
    var value = this.props.value || 'default value';
    return <div>{value}</div>;
  }
});

Do this for a few props across a few components and now you have a lot of redundant code. Starting with React v0.4, you can provide default values in a declarative way:

React.createClass({
  getDefaultProps: function() {
    return {
      value: 'default value'
    };
  }
  ...
});

We will use the cached result of this function before each render. We also perform all validations before each render to ensure that you have all of the data you need in the right form before you try to use it.


Both of these features are entirely optional. We've found them to be increasingly valuable at Facebook as our applications grow and evolve, and we hope others find them useful as well.