Making a 404Page with React Router and its gotcha

When deciding to write this article, I was skeptical. I mean there are countless of articles on this already so why do I want to reinvent the wheel. I decided to come with a gotcha [simple troubling bug associated with creating a 404 page].

If you try creating route for a big app, one of the things you would agree with me is the need to component-ize your routers and routes. Let me show what I mean.

// import Route, Router and Switch where necessary
import {Route, BrowserRouter as Router, Switch} from "react-router-dom"

//Routes.js
export const Routes = () => <React.Fragment>
   <Route path="/about">
     <About />
  </Route>
<Route path="/">
     <Home />
  </Route>
</React.Fragment>

// Router.js
import {Routes} from "./Routes"

export const Router = () => <Router>
   <Switch>
     <Routes />
  </Switch>
</Router>

Well if you do this, everything works fine until you try adding a 404Page.

//Routes.js
//ensure it comes last on your Routes children

export const Routes = () => <React.Fragment>
   ...
  <Route path="">
    <Page404 />
  </Route>
</React.Fragment>

Quickly will you notice that the 404 component appears in all other pages. Try creating a nav link and see this yourself. If you are like me, the next idea is to jump at the internet for an answer. Oops, sorry you would get so many irrelevant solutions cause this problem is a really tricky gotcha.

The solution is quite simple though. It is compulsory your routes are wrapped with Switch in the routes component so that it becomes.

//Routes.js
// replacing React.Fragment with Switch and removing Switch from the Router.js component
export const Routes = () => <Switch>
...
</Switch>

Well, that's all for creating 404 pages with React Router but I also helped you to see the common problem we encounter while trying to component-ize things. This is a definite guide to creating a 404 page and I hope you enjoyed it.