Catch-all routes in React Router

Currently, we have two paths set up, which are /app and /. If a user visits a non-existent path, such as /test, they will see an empty screen. The solution is to implement a route that matches any path. For simplicity, we redirect the user to the root of our application, but you could easily replace the redirection with a typical 404 page.

Add the following code to the router.js file:

class NotFound extends Component {
render() {
return (
<Redirect to="/"/> );
}
}

The NotFound component is minimal. It just redirects the user to the root path. Add the next Route component to the Switch in the Router. Ensure that it is the last one on the list:

<Route component={NotFound} />

As you can see, we are rendering a simple Route in the preceding code. What makes the route special is that we are not passing a path property with it. By default, the path is completely ignored and the component is rendered every time, except if there is a match with a previous component. That is why we added the route to the bottom of the Router. When no route matches, we redirect the user to the login screen in the root path, or, if the user is already logged in, we redirect them to a different screen using the routing logic of the root path. Our LoginRoute component handles this last case.

You can test all changes when starting the front end with npm run client and the back end with npm run server. We have now moved the current state of our application from a standard, single-route application to an application that differentiates the login form and the news feed based on the location of the browser.

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

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