- Full-Stack React Projects
- Shama Hoque
- 133字
- 2021-06-25 21:45:18
PrivateRoute component
The client/auth/PrivateRoute.js defines the PrivateRoute component as shown in an auth flow example from https://reacttraining.com/react-router/web/example/auth-workflow in the React Router documentation. It will allow us to declare protected routes for the frontend to restrict view access based on user auth.
mern-skeleton/client/auth/PrivateRoute.js:
import React, { Component } from 'react'
import { Route, Redirect } from 'react-router-dom'
import auth from './auth-helper'
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
auth.isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/signin',
state: { from: props.location }
}}/>
)
)}/>
)
export default PrivateRoute
Components to be rendered in this PrivateRoute will only load when the user is authenticated, otherwise the user will be redirected to the Signin component.
With the backend APIs integrated, and auth management helper methods ready for use in the components, we can start building the remaining view components.