¿Cómo puedo proteger rutas con la libreria react router dom v6?
Estoy creando mi primera app en react y me gustaria saber como puedo proteger determinadas rutas, en este caso todas las rutas que se encuentren en /dashboard/
en esta área solo podran ingresar usuarios que tengan credenciales, es decir que se encuentren registrados.
Públicas (cualquier persona puede ver estas páginas)
- http://localhost:3000/
- http://localhost:3000/register
- http://localhost:3000/login
Privadas (cuando el usuario inicia sesión):
- http://localhost:3000/dashboard/
- http://localhost:3000/dashboard/accounting
- http://localhost:3000/dashboard/employee
- http://localhost:3000/dashboard/ecommerce
package.json
"react-router-dom": "^6.0.1",
Index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
App.js
import AppRouter from "./routers/AppRouter";
import "./css/main.css";
function App() {
return (
<>
<AppRouter />
</>
);
}
export default App;
AppRouter
import { Route, Routes } from "react-router-dom";
import HomeView from "../components/views/public/HomeView";
import LoginView from "../components/views/public/LoginView";
import NotFound from "../components/views/public/NotFound";
import RegisterView from "../components/views/public/RegisterView";
const AppRouter = () => {
return (
<div>
<Routes>
{/* Rutas publicas: */}
<Route path="/" element={<HomeView />} />
<Route path="/login" element={<LoginView />} />
<Route path="/register" element={<RegisterView />} />
{/* Rutas privadas: */}
<Route path="dashboard/*" element={<Dashboard />} />
</Routes>
</div>
);
};
export default AppRouter;
Dashboard
import { Routes, Route } from "react-router-dom";
import AccountingHomeView from "../components/views/accounting/AccountingHomeView";
import { EcommerceHomeView } from "../ecommerce/EcommerceHomeView";
import EmployeeHomeView from "../employee/EmployeeHomeView";
import NotFound from "../public/NotFound";
import DashboardHomeView from "./DashboardHomeView";
const Dashboard = function () {
return (
<>
<Routes>
<Route path="/" element={<DashboardHomeView />} />
<Route path="accounting" element={<AccountingHomeView />} />
<Route path="employee" element={<EmployeeHomeView />} />
<Route path="ecommerce" element={<EcommerceHomeView />} />
<Route path="*" element={<NotFound />} />
</Routes>
</>
);
};
export default Dashboard;