How To Use React Router To Improve The UX Of Your React Application
Tags: react, javascript
Published: 2021-06-24 14:43:27

In this guide, you will create a custom 404 page and use react router to navigate to our custom 404 page whenever a user goes to the wrong page. We will cover a brief introduction to the essentials when working with react router to manage page routing in your react application.

What you will need:


- React Router [(installation link here)](https://reactrouter.com/web/guides/quick-start/installation)
- Your React application
- A custom 404 page



<br />
**React Router essentials:**

***React Router*** is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL  [*source*](https://www.geeksforgeeks.org/reactjs-router/) 

The main components to consider in our particular case include:

**BrowserRouter**: a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.

**Route**: Its most basic responsibility is to render some UI when its path matches the current URL.

**Switch**: Switch component is used to render only the first route that matches the location rather than rendering all matching routes. (We will use it in our guide to render our custom 404).

**Link**: The Link component is used to create links to multiple routes and to implement navigation within the app.


<br />

**The setup**

First we have to create a new React application by either using the `create-react-app` command or use an environment like  [codesandbox](https://codesandbox.io/)  or  [codepen](https://codepen.io/)  with a React template.

Install react router by running the command `npm install react-router-dom` or add it as a dependency on [codesandbox](https://codesandbox.io/) or [codepen.](https://codepen.io/)

The folder structure right now has a pages directory inside the src folder with all the pages that are necessary for this guide. We have four pages: home, about, dashboard, help and our custom 404 page. We also have a components folder with a navigation component.

![file-structure-custom-404.jpg](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6s7ydraj44eq52u8dxzf.jpg)

Inside our App.js file we import all the necessary modules from react router

```jsx
import { BrowserRouter as Router, Route } from "react-router-dom";

``` 

We then import our specific pages and components


```jsx
//pages
import Home from "./pages/Home";
import About from "./pages/About";
import Help from "./pages/Help";
import Dashboard from "./pages/Dashboard";
//components
import Nav from "./Components/Nav";
``` 
After everything is imported we setup our application to use the functionalities provided by react router. We wrap everything inside our Router component then import our Nav component to be rendered.


```jsx
export default function App() {
return (
   <Router>
         <Nav />
         <hr />
   </Router>
  );
}
``` 

After that we setup our page routing with the various route components that will navigate us to our desired pages


```jsx
export default function App() {
return (
   <Router>
      <Nav />
        <hr />
         <Route exact path="/">
           <Home />
         </Route> 
         <Route path="/about">
           <About />
         </Route>
         <Route path="/help"><Help />
           </Route>
         <Route path="/dashboard">
           <Dashboard />
         </Route>
    </Router>
  );
}
``` 

Our App.js file will look like this when everything is setup correctly


```jsx
import "./styles.css";
import { BrowserRouter as Router, Route } from "react-router-dom";

//pages
import Home from "./pages/Home";
import About from "./pages/About";
import Help from "./pages/Help";
import Dashboard from "./pages/Dashboard";

//components
import Nav from "./Components/Nav";

export default function App() {
  return (
    <Router>
      <Nav />
      <hr />
      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/help">
        <Help />
      </Route>
      <Route path="/dashboard">
        <Dashboard />
      </Route>
    </Router>
  );
}

``` 

{% codesandbox 3ndk8 %}

<br />
**Project scenario:**

Let's say we had a onetime bonus boost inside our fintech startup where we gifted every new user with double their initial investment. This promotion only ran for one evening and after it ended we decided as the dev team to remove that specific promotion page. 

Everyone that came to the page afterwards only saw a blank page which is bad user experience. How can we solve this?

<br />
**The solution, a custom 404 page:**

A custom 404 page would be the ideal solution to navigate users to our desired page, in this case the Home page.
For this special case we will be using the `<Switch>` component that is provided within react router. 

As previously discussed, we use the switch component to render only the first route that matches the specified location. With this in mind we will use the switch component to render out the first exact path that matches our desired page. 

We will also be adding a special route and passing it the `"*"` prop in order to render every time a path does not match. Inside this route component we will add our custom 404 page that will be rendered every time someone enters the wrong page on our app.


```jsx
export default function App() {
  return (
    <Router>
      <Nav />
      <hr />
      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
        <Route path="/about">
          <About />
        </Route>
        <Route path="/help">
          <Help />
        </Route>
        <Route path="/dashboard">
          <Dashboard />
        </Route>
        <Route path="*">
          <NotFound />
        </Route>
      </Switch>
    </Router>
  );
}

``` 

With that we have now improved the overall User Experience in our application. When we go to any page that is not in our application it returns a custom error page and guides us to the home page.

![Error-page-and-redirect-option.jpg](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mt3gcv7va9mg8q8vd23x.jpg)

{% codesandbox mffo2 %}

You can find the code to this guide  [Here](https://codesandbox.io/s/improved-ux-with-router-switch-added-mffo2?file=/src/App.js:343-817) .

Thank you for reaching this far and happy coding!!!