UNPKG

@navinc/base-react-components

Version:
45 lines (41 loc) 1.72 kB
import React from 'react' import propTypes from 'prop-types' import { Route } from 'react-router-dom' import LoadingView from './loading-view.js' export const GuardedRoute = ({ // A boolean condition that must be met for the route to render. condition, // Boolean that determines if the condition logic is still loading. Used when condition must fetch async data first. isConditionLoading, // Component to render when condition is still loading (optional). LoadingComponent = LoadingView, // Component to render when condition fails. This is required, since it will break React Router without one. FailureComponent, // The route component to render on condition success. component: Component, // The remaining props that we'll pass to React Router's Route component ...routeProps }) => { if (!FailureComponent) throw new Error('You must provide a FailureComponent to your guarded route.') return ( <Route {...routeProps} render={(props) => { if (LoadingComponent && isConditionLoading) return <LoadingComponent {...props} /> return !isConditionLoading && condition === true ? <Component {...props} /> : <FailureComponent {...props} /> }} /> ) } GuardedRoute.propTypes = { condition: propTypes.bool, isConditionLoading: propTypes.bool, LoadingComponent: propTypes.elementType, FailureComponent: propTypes.elementType.isRequired, component: propTypes.elementType, } /** * Create a GuardedRoute component with defaults. * @param {*} defaults Supports `condition`, `isConditionLoading`, `LoadingComponent`, and `FailureComponent`. */ export const createGuardedRoute = (defaults) => (props) => <GuardedRoute {...defaults} {...props} />