Guard middleware for React Router navigation
React Router Guards provides a middleware API for React Router, allowing you to perform complex logic between the call for navigation and the final render of a route.
Table of Contents
- Basic usage
- Code of Conduct
- About Upstatement
This package has the following peer dependencies:
$ npm install react-router-guards
$ yarn add react-router-guards
Then with a module bundler like webpack, use as you would anything else:
// using ES6 modules;// using CommonJS modulesconst GuardProvider = GuardProvider;const GuardedRoute = GuardedRoute;
Here is a very basic example of how to use React Router Guards.
import React from 'react';import BrowserRouter from 'react-router-dom';import GuardProvider GuardedRoute from 'react-router-guards';import About Home Loading Login NotFound from 'pages';import getIsLoggedIn from 'utils';const requireLogin = to from nextif tometaauthif;next;else;;const App =<BrowserRouter><GuardProvider = = =><Switch><GuardedRoute ="/login" = /><GuardedRoute ="/" = = /><GuardedRoute ="/about" = = /><GuardedRoute ="*" = /></Switch></GuardProvider></BrowserRouter>;
Check out our demos for more examples!
With the addition of guard middleware, the navigation lifecycle has changed.
Guard functions are the middleware between navigation and rendering.
Page components are used for setting loading and error pages.
GuardProvidercomponent is a high-level wrapper for your entire routing solution.
GuardedRoutecomponent acts as a replacement for the default
Routecomponent provided by React Router, allowing for routes to use guard middleware.
We've included some demos below to help provide more context on how to use this package!
The basic demo showcases some basic functionality of route guard API with an auth example.
The intermediate demo uses the PokéAPI to showcase how to use route guards for fetching data from an API.
We welcome all contributions to our projects! Filing bugs, feature requests, code changes, docs changes, or anything else you'd like to contribute are all more than welcome! More information about contributing can be found in the contributing guidelines.
Code of Conduct
Upstatement strives to provide a welcoming, inclusive environment for all users. To hold ourselves accountable to that mission, we have a strictly-enforced code of conduct.