2

I would like to update the value with a random number generated from the controller each time the div is clicked. Since the value is coming down statically from the Rails controller, does this mean I have to submit an ajax request to the route?

I understand that I can achieve the same effect by setting the state with some JavaScript code, but I want to know particularly if I can get this value from the controller.

Please help me fill in the handleClick function.

The react-rails gem is being used to render components in the view.

controller

class PostsController < ApplicationController
  def index
    @num = (1..100).to_a.sample
  end
end

view

<%= react_component("Num", { value: @num }) %>

component

var Num = React.createClass({
  getInitialState: function() {
    return {
      value: this.props.value
    };
  },

  handleClick: function() {

  },

  render: function() {
    return (
      <div className="num" onClick={this.handleClick}>
        { this.state.value }
      </div>
    );
  }
});
Dylan Richards
  • 796
  • 3
  • 9
  • 26
  • You can generate a random value in javascript http://stackoverflow.com/questions/4959975/generate-random-value-between-two-numbers-in-javascript. Also pretty sure that you have a syntax error at `
    – max May 26 '15 at 18:00
  • @maxcal -- Thanks for the suggestion. I know that I can do that. I want to get the data from the server on each click, though – Dylan Richards May 26 '15 at 18:17

1 Answers1

1

Short answer: Yes, you'd have to do an Ajax request.

More pragmatically, you can first update the state while waiting for the response from the Rails sever if you know the expected result. Then after the Ajax call is finished. Calibrate the return value with the pre-set value. If they are the same, React's virtual dom will be smart enough to not to update the UI.

yujingz
  • 2,271
  • 1
  • 25
  • 29