Search code examples
propertiesreactjsjsonprender

Passing props through in Render function


Any idea why I can log out the 'conditions' variable but cannot pass it through as a property in the render method? It is always undefined - "cannot read property 'conditions' of undefined".

Code below.

var React = require('react');
var ReactDOM = require('react-dom');

import Square from '../components/square.jsx';
import Circle from '../components/circle.jsx';
import Weather from '../components/weather.jsx';

var conditions = [];
$.ajax({
    url : "http://api.wunderground.com/api/xxxxxxxxxxxxxxxx/forecast10day/q/England/London.json",
    dataType : "jsonp",
    success : function(parsed_json) {
        conditions = parsed_json.forecast.simpleforecast.forecastday;
        console.log(conditions[1].conditions);
    }
});

ReactDOM.render(
    <div>
        <h1>Hello React!!!</h1>
        <SquareComp />
        <Square />
        <Circle width={100} height={100}/>
        <Weather cityName={'London'} weatherConditions={conditions[1].conditions} />
    </div>,
    document.getElementById('rootNode')

);

If I pre-fill the var all is well, so I'm guessing it's not receiving data before render is happening?

Thanks.


Solution

  • $.ajax is asynchronous. Immediately after calling it, it proceeds to calling ReactDOM.render, and, at this point conditions is still an empty array. You should render your components only after the Ajax call is finished loading the results sent from the server.

    Try the following:

    function renderConditions (conditions, domElement){
        ReactDOM.render(
            <div>
                <h1>Hello React!!!</h1>
                <SquareComp />
                <Square />
                <Circle width={100} height={100}/>
                <Weather cityName={'London'} weatherConditions={conditions[1].conditions} />
            </div>,
            domElement
        );
    }
    

    Define a function that render the data given as parameters.

    $.ajax({
        url : "http://api.wunderground.com/api/xxxxxxxxxxxxxxxx/forecast10day/q/England/London.json",
        dataType : "jsonp",
        success : function(parsed_json) {
            conditions = parsed_json.forecast.simpleforecast.forecastday;
            renderConditions(conditions, document.getElementById('rootNode'));
        }
    });
    

    Call the function renderConditions passing the appropriate parameters in the ajax success callback function.