> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/undefined-1/react-with-typescript/react/4./3.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# 3) 라우팅

## 1. 라우팅(Routing)

**URL 경로에 따라 알맞은 Component를 보여주는 과정**을 라우팅이라고 부릅니다.\
ex) localhost:5173/home ->  Main Component 서비스\
&#x20;     localhost:5173/login -> Login Component 서비스

React는 이때 브라우저의 History API를 활용하여 주소값은 바꾸지만 **실제 페이지 이동은 하지 않고** , 최초 로딩한 HTML안에서 **url에 맞는 컴포넌트만 교체**합니다.

## 2. 사용방법

```javascript
npm i --save react-router-dom 
```

## 3. 주요 컴포넌트

| 컴포넌트              | 설명                                          |
| ----------------- | ------------------------------------------- |
| `<BrowserRouter>` | 전체 라우팅 시스템을 감싸주는 최상위 컴포넌트. 보통 `App.js`를 감쌈  |
| `<Routes>`        | 여러 개의 `<Route>`를 그룹으로 묶는 컴포넌트               |
| `<Route>`         | 특정 URL 경로에 어떤 컴포넌트를 보여줄지 설정                 |
| `<Link>`          | `<a>` 태그처럼 생겼지만 **페이지 새로고침 없이 이동**시켜주는 컴포넌트 |
| `<Navigate>`      | 코드 상에서 리다이렉트할 때 사용                          |
| `<Outlet>`        | **중첩 라우팅**에서 **자식 컴포넌트를 렌더링할 위치** 지정        |

* 라우터적용 예시

```tsx
import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  Navigate,
} from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/home">홈</Link>
        <Link to="/login">로그인</Link>
      </nav>
      <Routes>
        <Route path="/home" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/" element={<Navigate to="/home" />} />
      </Routes>
    </BrowserRouter>
  );
}
```

## 4. 주요 hook함수

### 1) useNavigate

* **프로그래밍 방식으로 페이지를 이동**할 수 있게 해주는 훅(Hook)
* 로그인 완료 후, 회원가입 후, 삭제 완료 후 등에서 자동 이동할 때 사용한다(리디렉트)
* window\.location을 통한 페이지 이동과 달리 Hitosry 를 조작하여 페이지 이동이 발생한것 처럼 보이게 한다.

```jsx
import { useNavigate } from "react-router-dom";

function Login() {
  const navigate = useNavigate(); 
  const onLoginSuccess = () => {
    navigate("/home");
  };
}
```

### 2) useParams

* URL 경로에 정의된 **파라미터 값을 추출**하는 데 사용하는 Hook
* 동적 라우팅과 함께 사용된다.

```jsx
<Route path="/user/:id" element={<User />} />

function User() {
  const { id } = useParams(); // id = "123"
}
```

### 3)  useLocation

* 현재 브라우저 주소창의 **전체 URL 정보를 객체로 제공**하는 훅

```jsx
function Page() {
  const location = useLocation();
  console.log(location.pathname); // 현재 경로
  console.log(location.search);   // ?page=1
}
```

## 5. 중첩 라우팅

* **부모-자식 관계로 구성된 UI에 사용합니다.**
* `/admin`에서는 `users`와 `settings`모두가 가지는 공톰 컴포넌트(`<AdminLayout/>` )를 렌더링하고
* `users`와 `settings`에서는 고유한 자식 컴포넌트(`<UserList/>` ,`<Settings/>` )를 렌더링합니다.

```jsx
<Route path="/admin" element={<AdminLayout />}>
  <Route path="users" element={<UserList />} />
  <Route path="settings" element={<Settings />} />

</Route>
```

* 부모 컴포넌트 예시

```jsx
import { Outlet } from "react-router-dom";

function AdminLayout() {
  return (
    <div>
      <h1>관리자 페이지</h1>
      <Outlet /> {/* 자식 컴포넌트가 이 위치에 렌더링됨 */}
    </div>
  );
}

```

## 6. 동적 라우팅

* `:파라미터명` 형식으로 **다양한 URL을 하나의 컴포넌트로 처리**할 수 있게 한다.
* useParams와 함께 사용하여 동적 파라미터에 할당된 데이터를 추출할 수 있다

```jsx
<Route path="/product/:productId" element={<ProductDetail />} />
```
