react 에서의 라우터
npm i react-router-dom
React는 기본적으로 SPA(Single Page Application) 개발을 위한 라이브러리로, 페이지 전환 없이 컴포넌트만 교체하는 방식으로 동작한다. 이때 사용자에게 여러 페이지를 제공하는 것처럼 보이게 하는 기술이 라우팅이다.
// React Router v6 기본 사용법
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">홈</Link>
<Link to="/about">소개</Link>
<Link to="/products">제품</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/products" element={<Products />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
주요 컴포넌트
- BrowserRouter: HTML5 History API를 사용해 UI와 URL을 동기화
- Routes: 여러 Route를 그룹화하고 가장 일치하는 하나를 렌더링
- Route: URL 경로와 렌더링할 컴포넌트를 매핑
- Link: 페이지 새로고침 없이 라우트 이동을 처리하는 컴포넌트
동적 라우팅
URL 파라미터를 사용해 동적 콘텐츠를 로드할 수 있다:
// 동적 라우팅
<Routes>
<Route path="/products" element={<Products />} />
<Route path="/products/:id" element={<ProductDetail />} />
</Routes>;
// ProductDetail.js
import { useParams } from "react-router-dom";
function ProductDetail() {
const { id } = useParams();
return <div>제품 ID: {id}의 상세 정보</div>;
}
중첩 라우팅
라우트 안에 라우트를 중첩시켜 복잡한 UI 구조를 만들 수 있다:
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route index element={<Overview />} />
<Route path="stats" element={<Stats />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>;
// Dashboard.js
import { Outlet } from "react-router-dom";
function Dashboard() {
return (
<div>
<h1>대시보드</h1>
<nav>
<Link to="/dashboard">개요</Link>
<Link to="/dashboard/stats">통계</Link>
<Link to="/dashboard/settings">설정</Link>
</nav>
<Outlet /> {/* 중첩된 라우트가 여기에 렌더링됨 */}
</div>
);
}
프로그래밍 방식 네비게이션
코드에서 페이지 이동을 제어할 수 있다:
import { useNavigate } from "react-router-dom";
function LoginButton() {
const navigate = useNavigate();
const handleLogin = () => {
// 로그인 로직
navigate("/dashboard");
};
return <button onClick={handleLogin}>로그인</button>;
}
라우트 보호하기
인증된 사용자만 접근할 수 있는 보호된 라우트 구현:
function ProtectedRoute({ children }) {
const isAuthenticated = checkIfUserIsAuthenticated();
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
}
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/admin"
element={
<ProtectedRoute>
<Admin />
</ProtectedRoute>
}
/>
</Routes>;
React Router는 SPA에서 전통적인 멀티페이지 애플리케이션처럼 URL 기반 네비게이션을 제공하면서도, 페이지 새로고침 없이 빠른 사용자 경험을 유지할 수 있게 해준다!