Can Reactjs be used as a View within Emberjs?

I’m using React as the equivalent of an Ember View in some of the performance-sensitive parts of our application. It was fairly easy to implement, the process was pretty much like using a jQuery plugin, you just need to hook up mounting and unmounting the React component in didInsertElement and willClearRender.

The main gotcha is that you need to make sure you call forceUpdate on the React component whenever your data is updated.

This is what the code looks like:

App.LibraryView = Ember.View.extend({
  didInsertElement: function() {
    this.set('reactComponent', ReactComponent({
      content: this.get('content'),
      view: this
    }));
    React.renderComponent(this.get('reactComponent'), this.get('element'));
  },

  willClearRender: function() {
    React.unmountComponentAtNode(this.get('element'));
  }
});

Within the React component you can then use this.props.content.get('...') and this.props.content.set('...') to get and set properties and this.props.view to access the Ember view instance. Note that within the React event handlers if you set a property using this.props.content.set you will need to explicitly tell React to re-render by calling this.forceUpdate().

The list on this page is implemented using React components: http://hummingbird.me/users/vikhyat/library

The source code is here: https://github.com/hummingbird-me/hummingbird/blob/3dcde76e906f86c438f4ca11fd54481e7bf8c53e/app/assets/javascripts/react/library.js.jsx

4 Likes