Skip to main content

Routing and Navigation

In our frontend application, we use React Router for handling routing and navigation. React Router is a popular routing library for React applications that provides declarative routing capabilities.

Installation

To install React Router Dom, you can use npm or yarn:


_10
npm install react-router-dom
_10
_10
or
_10
_10
yarn add react-router-dom

Building our Role-based access component

To build our Role-based access component, we’ll follow this process;

  • When an employee signs in, the employee’s role and JWT token are stored in the Auth state.

  • When this employee requests access to a protected route, our role-based access component will access the Auth state and retrieve the employee’s role.

  • The employee’s role will then be cross-checked with an array containing the required roles for that route.

  • If the user’s role matches the required role, access is granted, else access will be denied.

Here’s the code for this;


_20
import { useLocation, Navigate, Outlet } from "react-router-dom";
_20
import { useContext } from "react";
_20
import AuthContext from "../Context/authProvider";
_20
_20
import React from "react";
_20
_20
const Auth = ({ allowedRoles }) => {
_20
const { auth } = useContext(AuthContext);
_20
const location = useLocation();
_20
_20
return allowedRoles.find((role) => auth.role.includes(role)) ? (
_20
<Outlet />
_20
) : auth?.name ? (
_20
<Navigate to="/unauthorized" state={{ from: location }} replace />
_20
) : (
_20
<Navigate to="/register" state={{ from: location }} replace />
_20
);
_20
};
_20
_20
export default Auth;

With this done, we’ll wrap each protected route with this component and pass to this component the required role for each page;


_30
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
_30
import Home from './components/Home';
_30
import About from './components/About';
_30
import Contact from './components/Contact';
_30
import NotFound from './components/NotFound';
_30
_30
const App = () => {
_30
return (
_30
<Routes>
_30
<Route path="/" element={<Layout />}>
_30
<Route path="/linkpage" element={<LinkPage />} />
_30
<Route path="/register" element={<Register />} />
_30
<Route path="/signin" element={<Signin />} />
_30
<Route path="/unauthorized" element={<Unauthorized />} />
_30
<Route path="/home" element={<Home />} />
_30
<Route element={<Auth allowedRoles={["marketer"]} />}>
_30
<Route path="/marketers-only" element={<MarketersPage />} />
_30
</Route>
_30
<Route element={<Auth allowedRoles={["se"]} />}>
_30
<Route path="/se-only" element={<SEPage />} />
_30
</Route>
_30
<Route element={<Auth allowedRoles={["se"]} />}>
_30
<Route path="/hr-Only" element={<HRPage />} />
_30
</Route>
_30
</Route>
_30
</Routes>;
_30
);
_30
};
_30
_30
export default App;

With these done, every group has access to only their specific route.