Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mrbr/react-router-protected-switch
React Router Protected Context
https://github.com/mrbr/react-router-protected-switch
Last synced: 1 day ago
JSON representation
React Router Protected Context
- Host: GitHub
- URL: https://github.com/mrbr/react-router-protected-switch
- Owner: MrBr
- License: mit
- Created: 2020-12-26T11:06:07.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2021-12-09T11:21:50.000Z (about 3 years ago)
- Last Synced: 2025-01-11T09:43:57.652Z (6 days ago)
- Language: TypeScript
- Size: 7.81 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# React Router Protected Switch
A generic way for protecting/scoping react router routes with zero dependencies.
## Installation
`yarn add react-router-protected-switch`
## The problem
There are few common mistakes done with custom protected routes which this library aims to resolve.
* Validation happens even when the path isn't matched
* Validation is strongly related to the authorization
* Validation can't be scoped to the subtree## The solution
By connecting `Route` with `SwitchContext` we get the new `ProtectedRoute` component which doesn't change the `Route`
props interface (remains agnostic regarding protection; doesn't require any) but to redirect unwanted visits.## API
* `SwitchContext` - the context provider for the custom switch components
* `switchContext` - under the hood context
* `SwitchContextConsumer` - the context consumer for the custom protected routes
* `useSwitchContext` - useful for creating custom protected routes## Usage example:
Switch component:
```
const AuthSwitch = ({ isAuthenticated, children }) => {
const redirect = !isAuthenticated && '/login';return (
{children}
);
};
```In the Router tree:
```
// Scoped validation - all routes under the AuthSwitch are protected
// Routes outside the switch behave normally
```