React에서는 **싱글 페이지 애플리케이션(SPA, Single Page Application)**을 만들기 때문에 페이지를 이동할 때 전체 페이지를 새로고침하지 않고 **클라이언트 측 라우팅(Client-side Routing)**을 사용한다
이를 위해 React Router 라이브러리를 활용함
React Router란?
React Router는 URL을 기반으로 컴포넌트를 동적으로 렌더링할 수 있도록 도와주는 라이브러리
주요 기능:
- 페이지 이동(Route)
- 링크 이동(Link, NavLink)
- 파라미터 및 쿼리 스트링 처리
- 중첩 라우팅(Nested Routing)
- 리디렉션(Redirect)
설치 방법:
npm install react-router-dom
Route를 이용한 페이지 이동
Route는 특정 URL 경로에 따라 렌더링할 컴포넌트를 지정하는 역할을함
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
const Home = () => <h2>홈 페이지</h2>;
const About = () => <h2>소개 페이지</h2>;
const App = () => {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
};
export default App;
path="/" → Home 컴포넌트가 렌더링됨
path="/about" → About 컴포넌트가 렌더링됨
Routes를 사용하는 이유:
Switch(React Router v5) 대신 Routes(v6)를 사용해야 합니다.
Route의 component 대신 element 속성을 사용해야 합니다.
Link를 사용한 페이지 이동
기본적으로 <a> 태그를 사용하면 페이지가 새로고침되기 때문에 SPA 방식이 깨질 수 있습니다.
React Router에서는 <Link>를 사용하여 페이지를 이동
import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";
const Home = () => <h2>홈 페이지</h2>;
const About = () => <h2>소개 페이지</h2>;
const App = () => {
return (
<Router>
<nav>
<Link to="/">홈</Link> | <Link to="/about">소개</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
};
export default App;
<Link to="/">홈</Link> → 클릭하면 홈 페이지로 이동
<Link to="/about">소개</Link> → 클릭하면 소개 페이지로 이동
<a> 태그와 <Link>의 차이점
태그특징
<a href="/"> | 클릭 시 전체 페이지가 새로고침됨 |
<Link to="/"> | 클라이언트 사이드 네비게이션, 새로고침 없이 빠르게 이동 |
NavLink: 활성화 스타일 적용
NavLink는 Link와 동일하지만, 현재 경로에 따라 스타일을 동적으로 변경할 수 있음.
🔹 isActive 속성을 사용하여 현재 경로일 때 스타일 적용 가능
import { NavLink } from "react-router-dom";
const Navigation = () => {
return (
<nav>
<NavLink to="/" style={({ isActive }) => ({ color: isActive ? "red" : "black" })}>
홈
</NavLink>
|
<NavLink to="/about" className={({ isActive }) => (isActive ? "active" : "")}>
소개
</NavLink>
</nav>
);
};
동적 라우팅 (URL 파라미터)
URL에 변수를 포함하는 동적 라우팅을 구현할 수 있음.
import { useParams } from "react-router-dom";
const Profile = () => {
const { username } = useParams();
return <h2>{username}의 프로필 페이지</h2>;
};
const App = () => {
return (
<Router>
<Routes>
<Route path="/profile/:username" element={<Profile />} />
</Routes>
</Router>
);
};
/profile/john → john의 프로필 페이지
/profile/mike → mike의 프로필 페이지
정리
기능설명
<Route> | 특정 경로에 맞는 컴포넌트를 렌더링 |
<Routes> | 여러 개의 <Route>를 감싸는 컨테이너 (v6에서 필수) |
<Link> | 새로고침 없이 페이지 이동 |
<NavLink> | 현재 경로에 따라 스타일을 동적으로 변경 |
useParams() | URL의 파라미터 값을 가져옴 |
'Front-End > React' 카테고리의 다른 글
React-ContextAPI (0) | 2025.02.17 |
---|---|
React-기본 (0) | 2025.02.11 |
ReportWebVitals란? (0) | 2025.02.11 |