Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 443
James Avatar asked Jul 21 '18 15:07

James


3 Answers

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>
        );
    }
like image 62
Shubham Bhewanewala Avatar answered Nov 20 '22 16:11

Shubham Bhewanewala


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/

like image 39
Werlious Avatar answered Nov 20 '22 16:11

Werlious


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/

like image 2
Phillip Avatar answered Nov 20 '22 17:11

Phillip