💻 Exemplos: Capítulo 09: Roteamento SPA com React Router 6+ (Routes, Outlet, Guards)
Especialização Frontend com React & TypeScript • Demonstrações Práticas Executáveis
🎯 Contexto e Objetivo Prático
Arquitetura de roteamento SPA com React Router Data API, Layouts aninhados com Outlet e rota protegida com Guards.
💻 Código Fonte React 19 (TSX)
// router-config.tsx
import React from "react";
import { createBrowserRouter, Outlet, Navigate, Link } from "react-router-dom";
// Layout Raiz com Navegação Global e Outlet
export function RootLayout() {
return (
<div className="min-h-screen flex flex-col">
<nav className="p-4 bg-slate-900 text-white flex gap-4 text-sm font-semibold">
<Link to="/" className="hover:text-cyan-400">Início</Link>
<Link to="/dashboard" className="hover:text-cyan-400">Dashboard</Link>
<Link to="/login" className="hover:text-cyan-400">Login</Link>
</nav>
<main className="flex-1 p-6">
<Outlet />
</main>
</div>
);
}
// Guard de Proteção de Rotas Autenticadas
interface ProtectedRouteProps {
isAuthenticated: boolean;
children: React.ReactElement;
}
export function ProtectedRoute({ isAuthenticated, children }: ProtectedRouteProps) {
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
}
export function DashboardHome() {
return <h2 className="text-xl font-bold">Painel de Métricas Corporativas (Protegido)</h2>;
}
export function LoginPage() {
return <h2 className="text-xl font-bold">Autenticação de Usuário</h2>;
}
// Definição da Árvore de Rotas
export const appRouter = createBrowserRouter([
{
path: "/",
element: <RootLayout />,
children: [
{ index: true, element: <p>Bem-vindo ao Portal de Cursos!</p> },
{
path: "dashboard",
element: (
<ProtectedRoute isAuthenticated={true}>
<DashboardHome />
</ProtectedRoute>
)
},
{ path: "login", element: <LoginPage /> }
]
}
]);
🖥️ Saída de Renderização Visual e Comportamento
[Navegação SPA Ativa]
URL: /dashboard
Renderiza: RootLayout -> ProtectedRoute (Auth=OK) -> DashboardHome
(Se não autenticado, redireciona instantaneamente para /login com replace)