Handling routes not found

In this section, we'll handle paths that aren't handled by any of the Route components. By following these steps, we'll start by understanding what happens if we put an unhandled path in the browser:

  1. Enter a path that isn't handled in the browser and see what happens: 

So, nothing is rendered beneath the header when we browse to a path that isn't handled by a Route component. This makes sense if we think about it.

  1. We'd like to improve the user experience of routes not found and inform the user that this is the case. Let's add the following highlighted route inside the Switch component:
<Switch>
<Redirect from="/home" to="/" />
<Route exact path="/" component={HomePage} />
<Route path="/search" component={SearchPage} />
<Route path="/ask" component={AskPage} />
<Route path="/signin" component={SignInPage} />
<Route component={NotFoundPage} />
</Switch>

In order to understand how this works, let's think about what the Switch component does again – it renders the first Route or Redirect component that matches the browser location. If we enter an invalid path, we already know that the existing Route components won't catch it. So, the Route component at the bottom of the Switch component with no path will catch an invalid path.

Note that it is important that we place the no- found route as the last route in the Switch component. If we place it above any other route, that route will never be rendered because the not-found route will always result in a match and the Switch component only renders the first match.

  1. The NotFoundPage hasn't been implemented yet, so let's create a file called NotFoundPage.tsx with the following content:
import React from 'react';
import { Page } from './Page';

export const NotFoundPage = () => <Page title="Page Not Found" />;
  1. Back in App.tsx, let's import the NotFoundPage component:
import { NotFoundPage } from './NotFoundPage';
  1. Now, if we enter an /invalid path in the browser, we'll see that our NotFoundPage component has been rendered: 

So, once we understand how the Switch component works, implementing a not-found page is very easy. We simply use a Route component with no path as the last element inside a Switch component.

At the moment, we are navigating to different pages in our app by manually changing the location in the browser. In the next section, we'll learn how to implement links to perform navigation within the app itself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.18.228