Ka Mok Ka Mok - 2 months ago 9
React JSX Question

In the react-rails gem, what's the difference between using the view helper react_component to render versus using ReactDOM.render?

So vanilla React allows you to use

ReactDOM.render
, but you have to tie it into the view via a JavaScript reference. Eg, in your JavaScript

ReactDOM.render(
<div>
<MyComponent>Sample Children</MyComponent>
</div>
, document.getElementById('content'));


And in your HTML

<div id="content"></div


But with the helper in the react-rails gem, you only do this in the HTML/view:

<%= react_component('MyComponent') %>


I can only see one downside with the helper, which is that you cannot add children to your component.

Any thoughts?

Answer

The react_component helper creates a target node, which eventually receives the component. Here's the relevant part of the gem's UJS:

https://github.com/reactjs/react-rails/blob/master/lib/assets/javascripts/react_ujs_mount.js#L87

A component rendered with <%= react_component %> may have children. Given a parent/child component like this:

var ChildComponent = React.createClass({
  render: function() { 
    return <p>{this.props.number}</p>
  }
})

var ParentComponent = React.createClass({
  render: function() {
    return (
      <div>
        <ChildComponent number="1" />
        <ChildComponent number="2" />
        <ChildComponent number="3" />
      </div>
    )
  }
})

These will both render 1 parent + 3 children:

<%= react_component("ParentComponent") %>

or, JS:

React.render(<ParentComponent />, targetNode)

Some advantages to the view helper:

  • no need to copy, paste and maintain DOM ids for "manually" mounting components
  • easy to provide props from Rails to React (eg react_component("ParentComponent", { numbers: [1,2,3] }))
  • Built-in mounting & unmounting for DOM events, Turbolinks or PJAX

Hope that helps!