Ad

State Not Passed Into Prop

- 1 answer

I'm using React with Rails 4.

I've got the following:

<%= react_component('Box',url: "blah", pollInterval: 2000) %>

and then my components:

var Box = React.createClass({
      getInitialState: function () {
    return {data: []};
  },
  loadStuffFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
        console.log(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentDidMount: function() {
    this.loadStuffFromServer();
    setInterval(this.loadStuffFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div>
        <Widget office="1" data="{this.state.data}"/>
      </div>
    );
  }
});

var Widget = React.createClass({
  render: function () {
     return (
        <div>
          {this.props.data}
        </div>
     )
  };
});

For the Box, I can see using React DevTools for Chrome that the state is being set to the JSON returned by the url. However for the Widget component, when I try to echo the props out it literally returns: {this.state.data}

So the props is being set, but to a string instead of the JSON array?

Ad

Answer

Any property inside quotes is a string:

<Widget office="1" data="{this.state.data}"/>

To use a JavaScript expression, use only the curlies:

<Widget office="1" data={this.state.data}/>
Ad
source: stackoverflow.com
Ad