Search code examples
javascriptruby-on-railsreactjsreact-rails

React-Rails: How to render a component with a ref?


At the moment I render my component inside a .erb file like this:

<%= react_component('Counter', number: @counter) %>

This component has a function that uses promised-xhr:

push: function(operation) {

    if(operation) {
      new_number = this.state.number +1;
    } else {
      new_number = this.state.number -1;
    }

 // This call works.
 // this.setState({number: new_number})

     XHR.post("/update", {
      data: {
        count: new_number
      }
    }).then(function(response) {
   // XHR.post is successful, so I can log the response.
      console.log(response.body.number);
   // But setState does not work because of 'this'
      this.setState({number: reponse.body.number})
    })

}

this.setState({number: response.body.number)} does not work because this is no longer the component. I am planning to use React.findDOMNode(this.refs.myComponent) to find my component and trigger the new state.

However, I can't figure how to use the react_component to assign a ref to my Counter component.


Solution

  • How about memoizing this, then using a local variable inside the callback?

    push: function(operation) {
      // ... 
      // Store `this` as local variable `_this`:
      var _this = this 
    
      XHR.post("/update", {/*...*/})
        .then(function(response) {
        // use local variable `_this`, which still refers to the component:
          _this.setState({number: reponse.body.number
        })
    }
    

    As a side note, ref might not help. After calling getDOMNode, you'd have a DOM node (browser built-in), not a React component.