Banner Banner - 3 months ago 14x
Javascript Question

Can't access state from child component

I'm trying to build a weather application. I have a searchbar component that fetches data via an api and sets the state of a weather prop which is initially null:

getInitialState: function() {
return {text: '', weather: null};
handleClick: function() {
WeatherApi.get('q=' + this.state.text).then(function(data) {
this.setState({weather: data})

What I want to do is pass the state of the weather prop to a child componenet once it is set via the user:

<TodaysWeatherContainer weatherData={} />

Then that gets accessed from the component like this:

var TodaysWeatherContainer = React.createClass({
render: function() {
return (

Now when I search for a city, I get the following error:

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {city, cod, message, cnt, list}). 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 of

If I add {} I get this error:

Uncaught TypeError: Cannot read property 'city' of null

This is where i'm getting confused. How can it be null when an object is being returned with this.props.weatherData?


It sounds like the data returned by the AJAX request is not just text (which would be a valid child node between those <p></p> tags), but an object, which is an invalid child.

Set the weather property of the state to a property of the object returned by the API response, not the whole object.

In response to your latest comment, it sounds like is itself an object that needs to be parsed. You can probably solve this problem yourself by better studying the API, which we have no knowledge about.

As @deowk points out in the comments, your second error resulted from the initial state of the parent component: {weather: null}. When the child component was first rendered, it attempted to find the city property on that null object. You no longer receive that error because you are now performing the lookup in the API callback, rather than in the child component itself.