To create any sort of "404 route", you simply have to add a route that matches any URL, and use it in a switch tag along with the valid routes. For instance:
<Switch>
<Route path ="/home" component={Home} />
<Route path ="/home/book" component={Book} />
<Route path ="/" component={FourZeroFour} />
</Switch>
You can also achieve the same effect by not using a Switch, and instead using exact on every route except the final one:
<Route path ="/home" component={Home} exact />
<Route path ="/home/book" component={Book} exact />
<Route path ="/" component={FourZeroFour} />
But what if you have a route that potentially matches both invalid and valid URLS, for instance:
<Route path ="/home/book/:bookId" component={SpecificBook} />
(where :bookId could be undefined)
In that case, you'll instead want to check the URL parameter's validity inside your component. For instance, your SpecificBook component might do the following:
const SpecificBook = ({ bookId } ) => {
if (bookId === 'undefined') return <Redirect to="/404" />;
// rest of component
}
You could also use history.push, but the Redirect tag will do more than just add a history entry; it will simulate a (server-side) redirect.