Friday, 16 October 2020

"Objects are not valid as a React child. If you meant to render a collection of children, use an array instead." error

I am trying to pass a user object as the value of my React Context.Provider as in <UserContext.Provider value={user} />. However, React does not like the idea of passing objects as children. Here is the error message I get:

Error: Objects are not valid as a React child (found: object with keys {id, username, first_name, last_name, email, avatar}). If you meant to render a collection of children, use an array instead.

I hope somebody can help. Here is my React component where all this happens:

class MyApp extends App {
  constructor(props) {
    super(props);
    this.state = {
      user: {},
      authenticating: false,
    };
  }

  logout = () => {
    ...
  };

  render() {
    const { Component, pageProps } = this.props;
    const user = {
      user: this.state.user,
      logout: this.logout,
    };
    return (
      <>
        {!this.state.authenticating && (
          <UserContext.Provider value={user}>
            <Navbar />
            <Component {...pageProps} />
          </UserContext.Provider>
        )}
      </>
    );
  }
}

Interestingly, when I change

const user = {
  user: this.state.user,
  logout: this.logout,
};

to (for example)

const user = {
  username: this.state.user.username,
  logout: this.logout,
};

everything works very well.

So (as the error message above sort of implies) the problem lies in passing this.state.user to my context provider. Why? How can I solve this?

Additionally, here is my <Context.Consumer />:

  <UserContext.Consumer>
    {user => (
      <>
        {user.user ? (
          <>
            <Avatar user={user.user} />
            <Button onClick={user.logout}>Logout</Button>
          </>
        ) : (
          <>
            <Nav.Link href="/users/login">Log in</Nav.Link>
            <Nav.Link href="/users/signup">Sign up</Nav.Link>
          </>
        )}
      </>
    )}
  </UserContext.Consumer>

Finally, here is my <Avatar />:

function Avatar({ user }) {
  return <Nav.Link href="/users/login">{user}</Nav.Link>;
}


from "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead." error

No comments:

Post a Comment