Vishnu Paspunoor Vishnu Paspunoor - 6 months ago 39
JSON Question

Rendering json data in multiple react.js components

I want to fetch some values from a json file and render them in multiple components. This code doesn't seem to work. Please suggest any changes. probably there are some issues with scope.

var App = React.createClass({

getInitialState: function(){
return { myData: [] }

},
showResults: function(response){
this.setState(
{myData: response}
)
},

loadData: function(URL) {
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: URL,
success: function(response){
this.showResults(response)
}.bind(this)
})
},

render: function(){
this.loadData("fileLocation/sample.json");
return(
<div>
{myData.key1}
<Component1 value={myData.key2} />
<Component2 value={myData.array[0].key3}/>
</div>
)
}
});

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

var Component2 = React.createClass({
render: function () {
return(
<div>{this.props.value}</div>
)
}
});
ReactDOM.render(<App/>, document.getElementById('content'));


This is sample.json file I'm trying to fetch from. Even this shows a syntax error

{
key1:"value1",
key2:"value2",
array: [
{key3:"value3"},
{key4:"value4"}
]
}

Answer

Properly call showResults at loadData [1]:

var App = React.createClass({

    getInitialState: function(){
      return { myData: [] };
    },

    showResults: function(response){
        this.setState({
            myData: response
        });
    },

    loadData: function(URL) {
      var that = this;
      $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function(response){
          that.showResults(response);
        }
      })
    },

Move loadData from render to componentDidMount [2], and properly access myData [3]:

    componentDidMount: function() {
      this.loadData("fileLocation/sample.json");
    },

    render: function(){
      return(
        <div>
        {this.state.myData.key1}
        <Component1 value={this.state.myData.key2} />
        <Component2 value={this.state.myData.array[0].key3}/>
        </div>
      )
    }
});

Keep Component1 and Component2 as they already are:

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

var Component2 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
});
ReactDOM.render(<App/>, document.getElementById('content'));