react-router-guards
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 - IntermediateRequirements
This package has the following peer dependencies:- React v16.8.0+ (for hooks ⚓️)
- React Router DOM v5.0.0+
Installation
With npm:$ npm install react-router-guards
With yarn:
$ yarn add react-router-guards
Then with a module bundler like webpack, use as you would anything else:
// using ES6 modules
import { GuardProvider, GuardedRoute } from 'react-router-guards';
// using CommonJS modules
const GuardProvider = require('react-router-guards').GuardProvider;
const GuardedRoute = require('react-router-guards').GuardedRoute;
Basic usage
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, next) => {
if (to.meta.auth) {
if (getIsLoggedIn()) {
next();
}
next.redirect('/login');
} else {
next();
}
};
const App = () => (
<BrowserRouter>
<GuardProvider guards={[requireLogin]} loading={Loading} error={NotFound}>
<Switch>
<GuardedRoute path="/login" exact component={Login} />
<GuardedRoute path="/" exact component={Home} meta={{ auth: true }} />
<GuardedRoute path="/about" exact component={About} meta={{ auth: true }} />
<GuardedRoute path="*" component={NotFound} />
</Switch>
</GuardProvider>
</BrowserRouter>
);
Check out our demos for more examples!
Concepts
Navigation lifecycle
With the addition of guard middleware, the navigation lifecycle has changed.
Guard functions
Guard functions are the middleware between navigation and rendering.
Page components
Page components are used for setting loading and error pages.
Guard Provider
The GuardProvider
component is a high-level wrapper for your entire routing solution.
Guarded Route
TheGuardedRoute
component acts as a replacement for the defaultRoute
component provided by React Router, allowing for routes to use guard middleware.
Demos
We've included some demos below to help provide more context on how to use this package!Basic
Demo + SourceThe basic demo showcases some basic functionality of route guard API with an auth example.
Intermediate
Demo | SourceThe intermediate demo uses the PokéAPI to showcase how to use route guards for fetching data from an API.