Uncaught Error: Objects are not valid as a React child

Situation: You create a class extending React.Component and want to declare it as a private variable; to update and call methods and then want to display it in the render method of the parent container. Straight forward:

this._myHappyClass = new HappyClass({someProperty: true});

Here we construct the class, which extends React.Component. Then we display it in the render method of the parent container:


public render(): React.ReactElement {

    return (
        <div>{this._myHappyClass}</div>
    ); 

}

And boom, screen blank, console displays error:

Uncaught Error: Objects are not valid as a React child (found: object 
with keys {props, context, refs, updater, state, updateDimensions}). 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 `HappyClass`.

I ran into this newbie problem and it took me a while to understand what was going on. The error seems to suggest the element I was trying to display for some reason isn’t a react child. It can’t display it. But my class is extending React.Component so what’s going on? I tried to cast it thinking that might be the issue, but still no luck. The solution is simple:

public render(): React.ReactElement { 

    return (
        {this._myHappyClass.render()}
    ); 

}

Just a small change, instead of putting the variable in the render method, call it’s render method instead, and this will return the React.Component. It makes sense right? If you just put the variable in there it’s trying to display a class, which is just an object, it’s just data. It’s the Render method that actually has anything to display.

Like I said, it’s a simple stupid problem but for a beginner in React this might help you save some time.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s