score:6

Accepted answer

You could just make a reusable component NoMatch and included at the bottom of your Switch.
For example:

<Switch>
    <Route exact path='/a/dashboard' component={ADashboard}/>
    <Route exact path='/a/payments' component={APayments}/>
    <Route exact path='/a/account' component={AAccount}/>
    <Route component={Notfound} />
</Switch>

Make sure to put it at the very end So, if no other route was matched, that one would be displayed.


Or you can make a simple custom function which you can reuse depending on your needs:

You could do this if the undefined path is not clear:

const createRedirect = to => () => <Redirect to={to} />
// ...
<Route path="/*" component={createRedirect('/foo')} />

To implement a redirect fallback in a switch, you need to do:

<Switch>
  <Route path="/foo" component={Bar}/>
  <Route path="/bar" component={Baz}/>
  <Route render={() => <Redirect to="/foo"/>}/>
</Switch>

Or you can take the longer approach and make it programmatically redirect. Here is a reference of a reusable component, or at least reusable logic that you could implement to your needs: Reference


Related Query

More Query from same tag