react-router-dom 이란

react는

spa(single page application) 이다. spa특성상 페이지를 새로고침하지 않으면서 화면을 전환해야 한다.이 때 화면 전환을 위해 react-router가 필요하며 별도의 패키지를 설치해야 한다.

 

- react-router : 웹&앱

- react-router-dom : 웹

- react-router-native : 앱

 

react-router 에는 세 가지 종류가 있는데 나는 웹에서 사용하기 위해 react-router-dom을 사용하였다.

 

아래 주소에서 사용법 및 예제를 확인할 수 있다.

https://reacttraining.com/react-router/web/example/basic

 

React Router: Declarative Routing for React

Learn once, Route Anywhere

reactrouter.com

 

 

react-router-dom 사용하기
npm install react-router-dom --save

먼저 npm으로 설치를 진행한다.

 

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

react-router-dom을 사용하기 위해 import가 필요하다.

 

function App() {
  return (
    <Router>
    <div>
      <hr />

      {/*
        A <Switch> looks through all its children <Route>
        elements and renders the first one whose path
        matches the current URL. Use a <Switch> any time
        you have multiple routes, but you want only one
        of them to render at a time
      */}
      <Switch>
        <Route exact path="/" component={LandingPage} />
        <Route exact path="/login"  component={LoginPage} />
        <Route exact path="/register" component={RegisterPage} />
      </Switch>
    </div>
  </Router>
  );
}

App.js에 다음과 같이 router를 설정해 주었다.

  • BrowserRouter(Router) - <Route>와 <Redirect> 컴포넌트가 함께 유기적으로 동작하도록 묶어주는데 사용. history API를 사용해 URL과 UI를 동기화하는 라우터
  • Route - 컴포넌트의 속성에 설정된 URL과 현재 경로가 일치하면 해당하는 컴포넌트, 함수를 렌더링한다.
  • Switch - 자식 컴포넌트 Route또는 Redirect중 매치되는 첫 번째 요소를 렌더링한다. Switch를 사용하면 하나의 매칭 요소만 렌더링한다는 점을 보장해준다. 사용하지 않을 경우 매칭되는 모두를 렌더링한다.

+ Recent posts