How to define fallback route properly in react-router-dom

Just place a redirect at the bottom like this and wrap your routes with Switch:

<Router>
    <Switch>
        <Route exact path='/' component={Home}/>
        <Route path='/about' component={About}/>
        <Route path='/code' component={Code}/>

        // Redirect all 404's to home
        <Redirect to='/' />
    </Switch>
</Router>

<Router>
    <Switch>
        // ...your routes and then
        <Route path="*" render={() => <Redirect to="/" />}
    </Switch>
</Router>

You need to do it inside a <Switch> component.

// IMPORT

import {
  BrowserRouter as Router,
  Route,
  Link,
  Switch,
  Redirect
} from "react-router-dom";

---------- 
// USAGE

<Switch>
  <Route path="/" exact component={Home} />
  <Redirect from="/old-match" to="/will-match" />
  <Route path="/will-match" component={WillMatch} />
  <Route component={NoMatch} />
</Switch>

As you can see from React Router Docs.

Switch

Renders the first child <Route> or <Redirect> that matches the location.

How is this different than just using a bunch of s?

<Switch> is unique in that it renders a route exclusively. In contrast, every <Route> that matches the location renders inclusively. Consider this code:

<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>

If the URL is /about, then <About>, <User>, and <NoMatch> will all render because they all match the path. This is by design, allowing us to compose <Route>s into our apps in many ways, like sidebars and breadcrumbs, bootstrap tabs, etc.

Occasionally, however, we want to pick only one <Route> to render. If we’re at /about we don’t want to also match /:user (or show our “404” page). Here’s how to do it with Switch:

import { Switch, Route } from 'react-router'

<Switch>
 <Route exact path="/" component={Home}/>
 <Route path="/about" component={About}/>
 <Route path="/:user" component={User}/>
 <Route component={NoMatch}/>
</Switch>