2

I want to do something like this where if no route matches I instantly redirect to '/'. With the code below when I hit the path that doesn't exist I get Nothing was returned from render

    <Switch>
      <Route exact path="/" component={UnAuth} />
      <PrivateRoute exact path="/:contentId" component={Content} />
      <Redirect to="/" />
   // <Redirect from='*' to='/' /> doesn't work as well
    </Switch>
karolis2017
  • 2,195
  • 8
  • 24
  • 49

1 Answers1

1

If you want a "catch all route" that will redirect to wherever ("/")

so you will first to create a "catch all" route

<Switch>
  <Route exact path="/" component={UnAuth} />
  <PrivateRoute exact path="/:contentId" component={Content} />
  //...all of your routes here

  // this route will catch any route that wasnt matched in previous routes
  <Route component={RedirectToMain}/> 

</Switch>

and the component that will get all the routes and redirect: It will only do redirection to / if you want more logic you can just create a class that will handle anything else.

const RedirectToMain = _ => {
    return (
        <Redirect to="/" />
    );
}
Tzook Bar Noy
  • 11,337
  • 14
  • 51
  • 82