React router v4 redirect when no match

Egor picture Egor · May 15, 2018 · Viewed 18.8k times · Source

I'm new to react-router (and client side routing in general) so I might be thinking about this all wrong. Sorry in advance if that is the case...

Basically just want to implement 3 simple rules:

  • if no user, redirect to '/login'
  • else if route doesn't exist, redirect to '/' (root)
  • else let user go to requested route

I keep track of the user in this.state.user. My current router seems to follow the first 2 rules, but only lets the authenticated user see the home page ('/profile' redirects to '/') so I know I'm doing something wrong but can't figure out what.

 <Router>
    {this.state.user ? (
      <Switch>
        <Route path="/" exact component={Home}/>
        <Route path="/profile" exact component={Profile}/>
        <Route render={() => (<Redirect to="/" />)}/>
      </Switch>
    ) : (
      <Switch>
        <Route path="/login" exact component={Login}/>
        <Route render={() => (<Redirect to="/login" />)}/>
      </Switch>
    )}
 </Router>

Any advice is appreciated. Thank you

Answer

GG. picture GG. · Sep 8, 2018

For anybody arriving here looking for how to redirect if none of the routes matches:

<Switch>
  // ... your routes
  <Route render={() => <Redirect to="/" />} />
</Switch>

Note that the routes have to be direct children of the <Switch>, e.g. this doesn't work:

<Switch>
  <Fragment>
    // ... your routes
    <Route render={() => <Redirect to="/" />} />
  </Fragment>
</Switch>

(maybe fixed in more recent versions of react-router)