My React routes are defined as follows:
...
<Route component={Header} />
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={Footer} />
...
I want to define a catch all route that catches anything that does not match the Landing, About or Contact routes, and instead redirects to a 404 Not found page. How can I do it with React Router 4?
Try this implementation
const AppRouter = (props) => {
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={NotFoundPage} />
</Switch>
<Footer />
</div>
</BrowserRouter>
);
}
Not sure if this will work for you as I have some 3rd party babel wrappers in use, but I get away with declaring all my routes then last putting
<Route path="/*" render={() => <SomeComponent /* possible prop injection */ />}/>
I've used this fairly frequently, but you can also use
<Route render={() => <SomeComponent />} />
I don't use this much as I prefer more landmarks in my code, but I got the above from https://tylermcginnis.com/react-router-handling-404-pages/
React has a component called switch from 'react-router-dom'
So By wrapping your Routes inside of Switch, React Router will only render the first Route that matches. Meaning all other routes that don't match will be caught by specifying a route that doesn't have a attribute. See https://ui.dev/react-router-v4-handling-404-pages/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With