Last active
November 22, 2021 18:19
-
-
Save akursat/41b95fa51bd70d56ce82e5a8cdd82daf to your computer and use it in GitHub Desktop.
React router v6 PrivateRoute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useSelector } from 'react-redux' | |
import { Navigate } from 'react-router-dom' | |
import AccessDenied from './pages/AccessDenied' | |
import { ROLE } from './features/auth/auth' | |
import { selectCurrentUser, selectIsAuthenticated } from './features/auth/authSlice' | |
interface Props { | |
component: React.ComponentType | |
path?: string | |
roles: Array<ROLE> | |
} | |
export const PrivateRoute: React.FC<Props> = ({ component: RouteComponent, roles }) => { | |
const user = useSelector(selectCurrentUser) | |
const isAuthenticated = useSelector(selectIsAuthenticated) | |
const userHasRequiredRole = user && roles.includes(user.role) ? true : false | |
if (isAuthenticated && userHasRequiredRole) { | |
return <RouteComponent /> | |
} | |
if (isAuthenticated && !userHasRequiredRole) { | |
return <AccessDenied /> | |
} | |
return <Navigate to="/" /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment