Handle Protected Routes in React app with the react-router-dom v6

React Protected Routes with react-router-dom v6
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Outlet />
</div>
);
}

function App() {
return (
<Routes>
<Route path="/" element={<Dashboard />}>
<Route
path="messages"
element={<DashboardMessages />}
/>
<Route path="tasks" element={<DashboardTasks />} />
</Route>
</Routes>
);
}
import { Outlet, Navigate } from 'react-router-dom';const ProtectedRoute = () => {
if (/* Check Login or Access Token here */) {
return <Outlet />;
} else {
return <Navigate to="/login" />;
}
}
export default ProtectedRoute;
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route element={<ProtectedRoute />}>
<Route path="/dashboard" element={<Dashboard />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store