the_
the_

Reputation: 1173

Objects not valid issue

I have the following component that is a lot like the React.js main tutorial. Basically, I have an api that I'm pulling from and trying to load the data:

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

However when I put blah there, I get the error: Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {items}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method ofBox.

I call my component with react rails and <%= react_component('Box',url: "URLHERE", pollInterval: 1000) %>

Upvotes: 0

Views: 328

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Use Array (data.items) instead of Object

var blah = this.state.data.items;
__________________________^^^^^^___


render: function () {
   var blah = this.state.data.items.map(function (item) {
     return <p>
       { item.content }
     </p>;
   });

   return <div>
     { blah }
   </div>;
}

Upvotes: 2

bozzmob
bozzmob

Reputation: 12574

Adding to what Alexander said, you don't have to assign state's value to a variable. You can directly do- inside the div tag

<div> { this.state.data.items } <div>

And Use a .map to get the values.

{this.state.data.items.map(objval =>
  <div>
   {objval.name}
  </div>
)}

Hope it helps :)

Upvotes: 0

Related Questions