Route Guard

  • 1. Step

    1. Install React Router

    
                  npm install react-router-dom
                

    2. Folder Structure

    
    
                src/
                  ├── App.js
                  ├── routes/
                  │   ├── PrivateRoute.js
                  ├── pages/
                  │   ├── Home.js
                  │   ├── Dashboard.js
                  │   └── Login.js
    
                  

    3. Create a PrivateRoute component

    
    
                  // routes/PrivateRoute.js
                  import { Navigate } from 'react-router-dom';
    
                  function PrivateRoute({ children }) {
                    const isAuthenticated = !!localStorage.getItem('token'); // or context/auth check
    
                    return isAuthenticated ? children : <Navigate to="/login" replace />;
                  }
    
                  export default PrivateRoute;
    
                  

    4. Define Routes in App.js

    
                    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
    import Home from './pages/Home';
    import Dashboard from './pages/Dashboard';
    import Login from './pages/Login';
    import PrivateRoute from './routes/PrivateRoute';
    
    function App() {
      return (
        <Router>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/login" element={<Login />} />
    
            <Route
              path="/dashboard"
              element={
                <PrivateRoute>
                  <Dashboard />
                </PrivateRoute>
              }
            />
          </Routes>
        </Router>
      );
    }
    
    export default App;
    
    
    

    Optional: Nested route

    
    
        const routes = createBrowserRouter(
        [
            {
                path: '/',
                element: <Root />,
                errorElement: <ErrorPage />,
                children: [
                    {
                        index: true,
                        element: <Home />
    
                    },
                    {
                        path: '/:id',
                        element: <PrivateRoutes><EstatesDetails /></PrivateRoutes>
                    },
                    {
                        path: 'profile',
                        element: <PrivateRoutes><Profile /></PrivateRoutes>
                    },
                    {
                        path: 'contact',
                        element: <Contact />
                    },
                    {
                        path: 'sign-up',
                        element: <SignUp />
                    },
                    {
                        path: 'sign-in',
                        element: <SignIn />
                    }
                ]
            }
        ]
        );