Ka Mok Ka Mok - 22 days ago 6x
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

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

<MyComponent>Sample Children</MyComponent>
, 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?


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


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 (
        <ChildComponent number="1" />
        <ChildComponent number="2" />
        <ChildComponent number="3" />

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!