Published on

React react-router-dom

Authors
  • avatar
    Name
    황도연
    Twitter

React 에서 react-router-dom을 사용하여 간단한 라우팅을 구현하는 방법에 대해 알아보겠습니다.
이 예제에서는 Vite와 TypeScript를 사용하고 있습니다. 프로젝트의 구조는 다음과 같습니다:

src/
├── App.tsx
├── index.css
├── main.tsx
├── pages
│   ├── about
│   │   └── index.tsx
│   └── home
│       └── index.tsx
├── routes
│   └── index.tsx
└── vite-env.d.ts

App.tsx

먼저, App.tsx 파일에서 전체 애플리케이션의 레이아웃을 설정합니다. 여기서는 AppRouter 컴포넌트를 호출하여 라우팅을 처리합니다.

import { AppRouter } from './routes/index'

const App = () => {
  return (
    <div className="App">
      <AppRouter />
    </div>
  )
}

export default App

routes/index.tsx

routes/index.tsx 파일에서는 실제 라우팅 로직이 구현됩니다. 여기서는 react-router-domBrowserRouter, Routes, Route 컴포넌트를 사용하여 경로를 설정합니다.

import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { Home } from '../pages/home'
import { About } from '../pages/about'

export const AppRouter = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  )
}

pages/home/index.tsx 와 pages/about/index.tsx

pages 디렉토리 안에는 각각의 페이지 컴포넌트가 위치합니다. 예를 들어, Home 페이지와 About 페이지는 아래와 같이 구성됩니다.

export const Home = () => {
  return (
    <div>
      <div>this is the home page</div>
    </div>
  )
}

export const About = () => {
  return (
    <div>
      <div>this is the about page</div>
    </div>
  )
}