React Router 개요

WooBuntu·2021년 3월 25일
0

알고 쓰자 리액트

목록 보기
2/11

React Router 공식 문서

Dynamic Routing

Static Routing : app이 렌더링(실행)되기 전에, 즉 app의 초기화 과정에서 routing을 설정하는 것

Dynamic Routing : app이 렌더링되는 동안 routing이 설정되는 것

React Router는 routing을 static한 configuration이 아닌, 그저 UI의 한 조각인 컴포넌트로 취급함으로써 Dynamic Routing을 실현한다.
(React Router를 사용할 때에는 routing을 컴포넌트로 간주하자)

// 스마트폰의 방향에 따라 '동적'으로 라우팅

const App = () => (
  <AppLayout>
    <Route path="/invoices" component={Invoices} />
  </AppLayout>
);

const Invoices = () => (
  <Layout>
    {/* always show the nav */}
    <InvoicesNav />

    <Media query={PRETTY_SMALL}>
      {screenIsSmall =>
        screenIsSmall ? (
          // small screen has no redirect
          <Switch>
            <Route
              exact
              path="/invoices/dashboard"
              component={Dashboard}
            />
            <Route path="/invoices/:id" component={Invoice} />
          </Switch>
        ) : (
          // large screen does!
          <Switch>
            <Route
              exact
              path="/invoices/dashboard"
              component={Dashboard}
            />
            <Route path="/invoices/:id" component={Invoice} />
            <Redirect from="/invoices" to="/invoices/dashboard" />
          </Switch>
        )
      }
    </Media>
  </Layout>
);

Primary Components

Routers

일반적으로 Router는 최상단 컴포넌트를 감싸게끔 되어 있다.

URL을 저장하는 방식과 웹 서버와 상호작용하는 방식에 따라 Router를 구분할 수 있다.

BrowserRouter

일반적인 URL 경로를 사용하는 라우터이다.
만약 SSR을 하면서 클라이언트 사이드에서 BrowserRouter로 라우팅을 한다면 서버 단에서 추가적으로 해야되는 작업이 있다.

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

function App() {
  return <h1>Hello React Router</h1>;
}

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

BroswerRouter상세

HashRouter

현재 위치를 hash(#)부분에 저장하는? URL 경로를 사용하는 라우터이다.
ex) http://example.com/#/your/page

URL경로에 #이 포함될 경우 브라우저는 리로딩 없이 자바스크립트를 불러오며, 동시에 URL을 브라우저 히스토리에 남긴다.

  • 리로딩을 하지 않고 각 #하위의 각 url경로에 맞춰 자바스크립트 이벤트 핸들러를 호출할 수 있다(AJAX요청)

  • URL이 브라우저 히스토리에 남으므로 history API를 사용할 수 있다.

이렇듯 #이 포함된 URL은 서버에 요청을 보내는 형태의 URL이 아니기 때문에 SSR을 하더라도 서버 단에서 추가로 해주어야 할 작업이 없다.

Route Matchers(Switch와 Router)

Switch가 렌더링되면, Switch의 자식 Route 중에서 현재 URL과 일치하는 Route를 찾아 렌더링하고 나머지 Route는 무시한다. 만약 일치하는 Route가 없는 경우에는 아무것도 렌더링하지 않는다(null 반환)

위에서부터 아래로 순차적으로 읽어 내려가면서 일치하는 Route를 찾기 때문에 더 '구체적인' 경로를 가진 Route를 위에 배치하고 보다 '일반적인' 경로를 가진 Route를 아래에 위치시켜야 한다.

Route 경로 탐색은 기본적으로 URL의 시작 부분이 일치하는지만 판단한다. 따라서 URL의 전체 경로와 일치하는지를 판별하고자 한다면 Route컴포넌트에 exact 속성을 부여해주어야 한다.

Route컴포넌트는 Switch컴포넌트 없이도 사용할 수 있지만 그다지 권장되지 않는 방식이다. 만약 단순히 match prop에 접근할 필요가 있는 거라면, useRouteMatch hook을 사용하는 것이 더 바람직하다.

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

function App() {
  return (
    <div>
      <Switch>
        {/* If the current URL is /about, this route is rendered
            while the rest are ignored */}
        <Route path="/about">
          <About />
        </Route>

        {/* Note how these two routes are ordered. The more specific
            path="/contact/:id" comes before path="/contact" so that
            route will render when viewing an individual contact */}
        <Route path="/contact/:id">
          <Contact />
        </Route>
        <Route path="/contact">
          <AllContacts />
        </Route>

        {/* If none of the previous routes render anything,
            this route acts as a fallback.

            Important: A route with path="/" will *always* match
            the URL because all URLs begin with a /. So that's
            why we put this one last of all */}
        <Route path="/">
          <Home />
        </Route>
      </Switch>
    </div>
  );
}

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById("root")
);
<Link to="/">Home</Link>
// <a href="/">Home</a>

to prop이 현재 경로와 일치할 때 styling을 적용할 수 있는 컴포넌트

<NavLink to="/react" activeClassName="hurray">
  React
</NavLink>

// When the URL is /react, this renders:
// <a href="/react" className="hurray">React</a>

// When it's something else:
// <a href="/react">React</a>

Redirect

Redirect가 렌더링되면 to prop이 가리키는 경로로 강제 이동된다.

<Redirect to="/login" />

0개의 댓글