728x90
728x90

라우터 설정 방법 (React Route)

들어가며

  • React Router(@react-router-dom@)을 이용하여 라우터를 설정하는 방법을 정리해본다.

 

방법

패키지 설치하기

  • @react-router-dom@ 패키지를 설치하려면 터미널에 아래 명령을 실행한다.
$ npm install react-router-dom    # yarn add react-router-dom

 

방법 1

  • @createBrowserRouter@를 이용하는 방법이다.
import {
  createBrowserRouter,
  RouterProvider,
} from "react-router-dom";

import HomePage from "./pages/Home";
import ProductsPage from "./pages/Products";

const router = createBrowserRouter([
  { path: "/", element: <HomePage /> },
  { path: "/products", element: <ProductsPage /> },
]);

function App() {
  return <RouterProvider router={router} />;
}

export default App;

 

방법 2

  • @createRoutesFromElements@, @createBrowserRouter@를 이용하는 방법이다.
  • 라우터들을 정의할 때, @<Route>@ 태그로 라우팅할 컴포넌트들을 감싸준다. 
import {
  createBrowserRouter,
  createRoutesFromElements,
  RouterProvider,
  Route,
} from "react-router-dom";

import HomePage from "./pages/Home";
import ProductsPage from "./pages/Products";

const routeDefinitions = createRoutesFromElements(
  <Route>
    <Route path="/" element={<HomePage />} />
    <Route path="/products" element={<ProductsPage />} />
  </Route>
);

const router = createBrowserRouter(routeDefinitions);

function App() {
  return <RouterProvider router={router} />;
}

export default App;
728x90
728x90