Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invariant Violation: Objects are not valid as a React child (for nested objects)

Tags:

reactjs

in my react component I have an object user which looks like

{
  _id: xxx, 
  stats: {a: 1, b: 2, c: 3},
  shops: [s1, s2, s3] // s1, s2, s3 are all objects
  ...
}

And then in my code I specify that it is an object.

export class UserComponent extends React.Component<void, Props, void> {
  static propTypes = {
    user: PropTypes.array,
    fetchProfile: PropTypes.func.isRequired
  };

  componentDidMount() {
    this.props.fetchProfile();
  }

  render () {
    const { user } = this.props;
    return (
      <div className='container text-center'>
        {user}
        <Link to="/">homeE</Link>
      </div>
    )
  }
}

But when I run the code the error message says:

invariant.js:39 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {thumb, path, photo_id, shop_id, message, _id, date_added}). 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.invaria....

it seems that I can do something like createFragment(user). But this is not working for me because this object has a lot of nested objects like the above.

Does anyone know how do solve this?

like image 355
Shih-Min Lee Avatar asked Mar 19 '16 10:03

Shih-Min Lee


1 Answers

In that line you pass value of object type.

  <div className='container text-center'>
    {user} // this is an object
    <Link to="/">homeE</Link>
  </div>

In your case user must be a string type or React component(created by React.createElement) or array type of React elements.

If you need to render some data from user or pass it to another component, you can do so:

  <div className='container text-center'>
    <User data={user} />
    <Link to="/">homeE</Link>
  </div>

And, of course, you have to define User react component, which handle(render) properties of user object. In User component we can get user object through this.props.data

like image 104
Dmitriy Avatar answered Nov 09 '22 10:11

Dmitriy