Untitled

 avatar
unknown
plain_text
2 years ago
2.1 kB
11
Indexable
There are a few ways you can restrict access to the /admin page in your React application. One common approach is to use React Router to add authentication and authorization checks to the route that corresponds to the /admin page.

Here's an example of how you might use React Router to restrict access to the /admin page:

First, you'll need to install React Router by running the following command:
Copy code
npm install react-router-dom
Next, you'll need to import the Route component and the useEffect hook from react-router-dom in your App.js file:
Copy code
import { Route, useEffect } from "react-router-dom";
You'll then need to wrap the Route component that corresponds to the /admin page with an authentication check. You can do this by creating a higher-order component (HOC) that wraps the Route component and checks whether the user is logged in and is an admin. Here is an example:
Copy code
import { useAuth } from './context/auth-context';

function AdminRoute({ component: Component, ...rest }) {
  const { state: { isAuth, userRole } } = useAuth();
  return (
    <Route
      {...rest}
      render={(props) =>
        isAuth && userRole === 'admin' ? (
          <Component {...props} />
        ) : (
          <Redirect to="/" />
        )
      }
    />
  );
}
This HOC uses the useAuth custom hook to get the current authenticated state and user role of the user from the context. Then it check whether user is authenticated and is admin if true it renders the component else redirects to home page.

Finally, you can use the AdminRoute component in place of the Route component when defining the route for the /admin page. For example:
Copy code
<AdminRoute path="/admin" component={AdminPage} />
With this setup, only logged-in users with an "admin" role will be able to access the /admin page. Other users will be redirected to the homepage.

Please note that this is just a basic example, you should use your own checks and user authentication/authorization method in your own application.
Editor is loading...