본문 바로가기
Study/Udemy-React-완벽 가이드

19.1 리액트 라우터가 있는 SPA 다중 페이지 구축하기: 경로 정의 및 사용하기(feat. 유데미 React 완벽 가이드)

by NFAP0221S 2022. 6. 14.

https://www.udemy.com/course/best-react/

 

【한글자막】 React 완벽 가이드 with Redux, Next.js, TypeScript

Javascript부터 웹 어플리케이션 배포까지, React와 프론트엔드 최신 기술을 가장 쉽고 확실하게 배우는 법

www.udemy.com

이 게시물은 유데미 React 완벽 가이드 강의를 보고 메모를 남기는 게시물 입니다.


Route 컴포넌트

  • 특정 경로를 정의한 다음 URL에서 경로가 황성화될 때 로드되어야 하는 리액트 컴포넌트를 정의하는 컴포넌트

Route 가져오기

react-router-dom 에서 Route 컴포넌트를 가져온다.

import { Route } from "react-router-dom";

Route 설정하기

src에서 pages 폴더를 만들고 그 안에 컴포넌트를 2개 만들어준다.

저번 강의들에서는 components 폴더를 만들고 그 안에 컴포넌트를 만들어 주었는데, 라우터 설정을 하여 page 역할을

하는 컴포넌트는 pages 라는 폴더에서 작업을 하는게 가독성에 좋다.

// Products.js

const Products = () => {
  return <h1>The Products Page</h1>;
};

export default Products;
// Welcome.js

const Welcome = () => {
  return <h1>The Welcom Page</h1>;
};

export default Welcome;

 

App.js 에서 Route 설정을 해보자.

Route 컴포넌트를 사용하면된다. props 으로 path를 설정해야하는데 원하는 route로 설정을 하면된다.

// App.js

import { Route } from "react-router-dom";

import Welcome from "./pages/Welcome";
import Products from "./pages/Products";

function App() {
  return (
    <div>
      <Route path="/welcome">
        <Welcome />
      </Route>
      <Route path="/Products">
        <Products />
      </Route>
    </div>
  );
}

그다음 index.js 에서 react-router-dom 에서 BrowserRouter 를 가져와 App을 래핑하면 된다.

// index.js

import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";

import "./index.css";
import App from "./App";

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

브라우저에서 http://localhost:3000/welcome, http://localhost:3000/products 을 접속하여 확인해보자.