# Guarded Routes

Guarded Routes allow you to create a React Router route that will only load if a certain condition is met. If the condition is not met, then a `FailureComponent` will be loaded instead. Since some conditions require async data, you can also pass a prop to wait for the data to load before triggering a condition failure.

To create a Guarded Route, you use a factory function. This allows you to set defaults that all instances of that `GuardedRoute` will use. You can also override defaults in the `GuardedRoute` component itself on a per-route basis.

The reason we use a factory function rather than a provider is because you may want to create a variety of different Guarded Routes with different defaults. With a provider component, this wouldn't really be possible.

```js
import { createGuardedRoute, LoadingView } from '@navinc/base-react-components'
import chunks from './chunks'

const { isUserLoggedIn } = useUser()
const { isUserAdmin, loading } = useUserRoles()

const AuthRoute = createGuardedRoute({
  condition: isUserLoggedIn,
  LoadingComponent: LoadingView,
  FailureComponent: chunks.NotFoundPage,
})

const AdminRoute = createGuardedRoute({
  condition: isUserAdminRole,
  isConditionLoading: loading,
  LoadingComponent: LoadingView,
  FailureComponent: chunks.RestrictedPage,
})

<Switch>
  <Route path="/" component={chunks.HomePage} />

  <AuthRoute path="/dashboard" component={chunks.UserDashboardPage} />

  <AdminRoute path="/admin" component={chunks.AdminPage} />
  <AdminRoute path="/admin/users" component={chunks.AdminUsersPage} />
  <AdminRoute condition={isUserAdminRole && someOtherCondition} path="/admin/roles" component={chunks.AdminRolesPage} />
</Switch>
```
