skip to Main Content

I am using React-Router-Dom for page routes. I need to separate admin routes from public ones.Can anyone tell me how do i do it.

App.js

import { createBrowserRouter,RouterProvider } from "react-router-dom";
import HomePage from "./Pages/home";
import Contact from './Pages/contact';
import AboutPage from "./Pages/About";
import RootLayout from "./Pages/Root";
import ErrorPage from "./Pages/error";
import ProductPage from "./Pages/Product";
import ProductDetails from "./Pages/ProductDetails";

const router = createBrowserRouter([
  {
      path: '/',
      elements: <RootLayout />,
      errorElement: <ErrorPage />,
      children: [
        {path:'/', element:<HomePage />},
          { path: 'contact', element: <Contact /> },
          { path: 'about', element: <AboutPage /> },
          { path: 'product', element: <ProductPage /> },
          { path: 'product/:productId', element: <ProductDetails /> },
      ],
  },
]);

function App() {
  return (
  <RouterProvider router={router} />
  );
}

export default App;

I want admin Routes that are only accessible to admins only.

2

Answers


  1. Here is an example

    App.js

    import React from 'react';
    import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
    import PrivateRoute from './PrivateRoute';
    import Home from './components/Home';
    import Dashboard from './components/Dashboard';
    import Login from './components/Login';
    
    const App = () => {
      const isAuthenticated = true; //state determined from actual authentication logic
    
      return (
        <Router>
          <div>
            <Route exact path="/" component={Home} />
            <PrivateRoute
              path="/dashboard"
              component={Dashboard}
              isAuthenticated={isAuthenticated}
            />
            <Route
              path="/login"
              render={() =>
                isAuthenticated ? <Redirect to="/dashboard" /> : <Login />
              }
            />
          </div>
        </Router>
      );
    };
    
    export default App;
    

    PrivateRoute.js

    import React from 'react';
    import { Route, Redirect } from 'react-router-dom';
    
    const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => {
      return (
        <Route
          {...rest}
          render={(props) =>
            isAuthenticated ? (
              <Component {...props} />
            ) : (
              <Redirect to="/login" />
            )
          }
        />
      );
    };
    
    export default PrivateRoute;
    

    Reference article : https://coderomeos.org/create-private-authenticated-routes-in-react

    Login or Signup to reply.
  2. Here is an example how you can do it:

    import {
      createBrowserRouter,
      RouterProvider,
      Outlet,
      Navigate,
    } from 'react-router-dom';
    import HomePage from './Pages/home';
    import Contact from './Pages/contact';
    import AboutPage from './Pages/About';
    import RootLayout from './Pages/Root';
    import ErrorPage from './Pages/error';
    import ProductPage from './Pages/Product';
    import ProductDetails from './Pages/ProductDetails';
    
    function AdminRoute() {
      // somehow get the current user, let's say from the context
      const user = useUser();
      // somehow check that user is admin
      if (!isAdmin(user)) {
        return <Navigate to="/" />;
      }
      return <Outlet />;
    }
    
    const router = createBrowserRouter([
      {
        path: '/',
        element: <RootLayout />,
        errorElement: <ErrorPage />,
        children: [
          { path: '/', element: <HomePage /> },
          { path: 'contact', element: <Contact /> },
          { path: 'about', element: <AboutPage /> },
          {
            // let's say this is a protected route
            element: <AdminRoute />,
            children: [
              { path: 'product', element: <ProductPage /> },
              { path: 'product/:productId', element: <ProductDetails /> },
            ],
          },
        ],
      },
    ]);
    
    function App() {
      return <RouterProvider router={router} />;
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search