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 : ;
}
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 (
} />
} />
}
/>
);
}
export default App;
Optional: Nested route
const routes = createBrowserRouter(
[
{
path: '/',
element: ,
errorElement: ,
children: [
{
index: true,
element:
},
{
path: '/:id',
element:
},
{
path: 'profile',
element:
},
{
path: 'contact',
element:
},
{
path: 'sign-up',
element:
},
{
path: 'sign-in',
element:
}
]
}
]
);