theJuls theJuls - 1 year ago 76
React JSX Question

Looping through a JSON object's entries and through react state, getting 'state undefined'

Please forgive if I am way off target, but I am trying to set a component's state to a json object, so that I can render it with the component.

Here is what a currently have inside my component:

render: function() {
this.serverRequest = $.get(this.props.source, function (data) {
this.state.content = $.parseJSON(data);


return (

{Object.keys(this.state.content).map(function (key) {
return <div>Key: {key}, Value: {this.state.content[key]}</div>;


With this code I currently get:

Uncaught TypeError: Cannot read property 'state' of undefined

Anyone have any insight as to why this isn't working?

Answer Source

The problem is, the this inside the $.get() is not in the React's scope. And calling setState() inside render will throw an error. The following should help...

var App = React.createClass({
  getInitialState: function() {
    return {
      content: {},

  componentDidMount: function() {

  serverRequest: function() {
    var _this = this
    $.get(this.props.source, function(data) {
      _this.state.content = $.parseJSON(data);


  render: function() {
    return ( < div >

        Object.keys(this.state.content).map(function(key) {
          return <div > Key: {
          }, Value: {
          } < /div>;

      < /div >
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download