Jamie Aden
Jamie Aden

Reputation: 981

Objects are not valid as a React child using react router v4

This is my wrapper component aka auth component to allow only authed user to access.

Auth.js

render() {
    const { Component: component, ...rest } = this.props;

    return (
      <Route>
        {rest}
        render={props =>
          this.isAuth === true ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{
                pathname: "/login"
              }}
            />
          )
        }
      </Route>
    );
  }

What's wrong with it? Here's my route declaration

Index.js

render(
  <BrowserRouter>
    <div className="App">
      <Switch>
        <Route path="/login" component={Login} />
        <Auth path="/dashboard" component={Dashboard} />
      </Switch>
    </div>
  </BrowserRouter>,
  document.getElementById("root")
);

I've made a demo to reproduce the problem here https://codesandbox.io/s/5xm202p1j4

I used the same concept in the official doc, https://reacttraining.com/react-router/web/example/auth-workflow just that instead of making the auth.js a pure function I make it a class base container so that I can call api or check the token of the user exist or not in my localstorage, what's the problem exactly?

Upvotes: 1

Views: 1325

Answers (1)

Anthony
Anthony

Reputation: 6502

Did you mean to do something like this:

render() {
  const { Component: component, ...rest } = this.props;

  return (
    <Route
      {...rest}
      render={props =>
        this.isAuth === true ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login"
            }}
          />
        )
      }
    />
  );
}

By having rest and render in the <Route> tag so the rest are passed to the <Route>?

Upvotes: 1

Related Questions