How to Set a Default Page for All URLs using React Router
I needed a route in one my React applications that handled all unmatched requests, particularly to handle 404 (page not found) errors.
A Basic React Router Example
For example, what if I had this React Router code in App.js
?
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
const Home = () => <h1>Home!</h1>;
const About = () => <h1>About!</h1>;
const App = () => (
<Router>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Router>
);
export default App;
We can easily navigate to the /
and /about
routes, but what if a user navigates to /anythingelse
or /nonexistentpage
?
The Switch
Component
Fortunately, we can use the <Switch>
component, which renders the first <Route>
child that matches. It’s also important to note that a <Route>
with no path will always match.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = () => <h1>Home!</h1>;
const About = () => <h1>About!</h1>;
const NoMatch = () => <h1>404 Error: page does not exist!</h1>;
const App = () => (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route component={NoMatch} />
</Switch>
</Router>
);
export default App;
We can drop the path
attribute and just specify a component for any page that does not match /
or /about
.
This means that our NoMatch
component will render at the link /anythingelse
, /nonexistentpage
, and anything that’s not /
or /about
.
We can also have the route redirect to a custom 404 error page.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = () => <h1>Home!</h1>;
const About = () => <h1>About!</h1>;
const NoMatch = () => <h1>404 Error: page does not exist!</h1>;
const App = () => (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/error" component={NoMatch} />
<Redirect to="/error" />
</Switch>
</Router>
);
export default App;
In this case, /anythingelse
and /nonexistentpage
will redirect to /error
and display our NoMatch
component.