Search code examples
reactjsreact-router-v4

React-Router 4 catch all route


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?


Solution

  • 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>
            );
        }