React

[Router] React Router

Alexim 2022. 8. 21. 23:23

react router

  • v5에서 v6으로 업데이트되면서 많은 게 바꼈는데 기능상의 업데이트 보다는 문법이 많이 바뀜. 직관적으로 많이 바꼈다고 함. Reach Router라는 것과 합쳐져셔 많이 바꼈다고 함.
  • 문서를 볼 때 아래의 단어가 있다면 v5이다.
    • Switch (Routes로 바꼈다.)
    • exact (path와 정확하게 일치하는 경우에만 이동하라는 건데 v6에서 없어졌다.)
    • params
    • history.push or history.replay (useNavigate로 바꼈다.)
    • history.goback() (뒤로 가는 기능으로 navigate(-1)로 쓸 수 있다. 2페이지 전: -2)
  • react router는 눈속임이다. 페이지가 여러 개 있는 게 아니라 여러 개 있는 척 하는 것. (실제로는 페이지가 하나다.)
  • Main Conceps react router에 대해 더 깊게 들어가는 개념들

Routers

  • 앱을 브라우저의 URL에 연결해준다.
  • 앱을 연결하기 위해서는 최상위 컴포넌트를 Router로 감싸주어야 한다.
  • Router는 최상위 컴포넌트라고 생각하면.. 될듯 합니다. 뼈대라고 보면 된다.
  • Router 종류는 5가지가 있다.
  1. BrowserRouter
    • 웹 브라우저에서 React Router를 실행하기 위한 권장 인터페이스.
    • 제일 많이 쓴다고 함.
    • 브라우저에 내장되어 있는(built-in) history stack - HTML5 history AP(pushState, replaceState and the popstate event)를 사용해서 UI를 URL과 동기화된 상태로 유지한다.
  2. HashRouter
    • 어떤 이유로 URL을 서버에 보내지 않아야 하는 웹 브라우저에서 사용하기 위한 것
    • 서버에서 읽을 수 없기 때문에 Server Side Rendering으로 설정을 백업할 수는 없다.
    • 가장 큰 특징은 주소에 해쉬(#)가 붙고 검색 엔진이 읽지 못한다는 것
    • hash history를 지원하지 않는다.
    • 꼭 필요한 경우가 아니면 사용하지 않는 것이 좋다고 나와있음(공홈에)
  3. HistoryRouter
  4. MemoryRouter
  5. NativeRouter
  6. Router
  7. StaticRoute

용어 정리 https://itchallenger.tistory.com/566 님 블로그 참고

Components

  • Link
  • NavLink
  • Navigate
  • Outlet
  • Route
  • Routes

Navigating

  • URL이 변하는 것을 navigation이라고 한다. 방법에는 두 가지가 있다.
    1. Link
    2. navigate (hook, component)
  1. Link
    • 사용자가 클릭하거나 탭하여 다른 페이지로 이동할 수 있는 요소.
    • navigation의 기본 수단.
    • a <Link>renders an accessible <a> element with a real href that points to the resource it's linking to.
    • /로 시작하지 않는 상대 값은 상위 경로를 기준으로 확인된다. 즉 해당 값을 렌더링한 경로와 일치하는 URL 경로를 기반으로 빌드된다.
    • ..은 터미널의 cd와 같다.
    • with a .. behaves differently from a normal when the current URL ends with /. ignores the trailing slash, and removes one URL segment for each ... But an value handles .. differently when the current URL ends with / vs when it does not.
  2. navigate function
    • 이 함수는 useNavigate hook에서 반환되어 원할 때마다 URL을 변경할 수 있도록 한다.
    • 먼저 const navigate = useNavigate();로 선언을 해준다.
    • navigate("/주소") 하면 가려는 주소로 이동할 수 있다.
    • Link 대신 navigate를 사용할 때에는 충분한 이유가 있어야 한다.
  3. Navigate
    • 렌더링될 때 현재 위치를 변경한다. useNavigate의 컴포넌트 wrapper이다. useNavigate와 같은 props, 인자를 가진다.

Outlet

  • 자식 경로 요소를 렌더링하려면 부모 경로 요소에서 <Outlet>을 사용해야 한다. 이를 통해 하위 경로가 렌더링될 때 중첩된 UI가 표시된다. 부모 라우트가 정확히 일치하면 자식 인덱스 라우트를 렌더링하거나 인덱스 라우트가 없으면 아무것도 렌더링 하지 않는다. (Index Route란 부모 URL의 부모 Outlet에서 렌더링되는 Route가 없는 Child Route)
  • react router는 v6부터 outlet이라는 컴포넌트와 함께 컴포넌트 트리의 레이아웃에 직접적으로 관여한다. 강력한 능력이래용..
function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>

      {/* This element will render either <DashboardMessages> when the URL is
          "/messages", <DashboardTasks> at "/tasks", or null if it is "/"
      */}
      <Outlet /> // 자식이 렌더링 될 위치
    </div>
  );
}

function App() {
  return (
    <Routes>
      <Route path="/" element={<Dashboard />}> // 부모
        <Route
          path="messages"
          element={<DashboardMessages />} // 자식
        />
        <Route path="tasks" element={<DashboardTasks />} />
      </Route>
    </Routes>
  );
}

Routes and Route

  • Routes와 Route는 현재 location을 기반으로 React Router에서 무언가를 렌더링하는 주요 방법.
  • Route는 일종의 if statement와 같은 것이라고 생각할 수 있다. 만일 (if) path가 현재 URL과 일치한다면 그 라우트의 element를 렌더링 할 것이다.
  • Routes는 위치가 변경될 때마다 모든 children <Route> 요소를 살펴보고 가장 일치하는 항목을 찾고 UI의 해당 분기를 렌더링한다. <Route> 요소는 중첩된 URL 경로에 해당하는 중첩된 UI를 나타내기 위해 중첩될 수 있다. 상위 경로는 <Outlet>을 이용하여 하위 경로를 렌더링 한다.
<Routes>
  <Route path="/" element={<Dashboard />}>
    <Route
      path="messages"
      element={<DashboardMessages />}
    />
    <Route path="tasks" element={<DashboardTasks />} />
  </Route>
  <Route path="about" element={<AboutPage />} />
</Routes>
  • For example, in the following config the parent route renders an by default, so the child route will render without any surrounding UI. But the child route's path is /users/:id because it still builds on its parent.
  • <Route path="users"> <Route path=":id" element={<UserProfile />} /> </Route>

HOOKS

  • useHref
    • React Router 외부에서도 주어진 위치에 연결하는 데 사용할 수 있는 URL을 반환한다.
  • useInRouterContext
    • 만일 컴포넌트가 <Router>의 context에서 렌더된다면 "true"를 반환하고 그렇지 않으면 "false"를 반환한다.
  • useLinkClickHandler
  • useLinkPressHandler
  • useLocation
    -현재 locaton 개체를 반환한다. 현재 위치가 변경될 때마다 일부 side effect를 수행하려는 경우에 유용할 수 있다.
import \* as React from 'react';  
import { useLocation } from 'react-router-dom';

function App() {  
let location = useLocation();

React.useEffect(() => {  
ga('send', 'pageview');  
}, \[location\]);

return (  
// ...  
);  
}
  • 객체를 반환하며 이 객체는 현재 사용자가 보고있는 페이지의 정보를 지니고 있다. 이 객체에는 다음과 같은 값들이 있다.
    • pathname: 현재 주소의 경로 (쿼리스트링 제외)
    • search: 맨 앞의 ? 문자 포함한 쿼리스트링 값
    • hash: 주소의 # 문자열 뒤의 값 (주로 History API 가 지원되지 않는 구형 브라우저에서 클라이언트 라우팅을 사용할 때 쓰는 해시 라우터에서 사용합니다.)
    • state: 페이지로 이동할때 임의로 넣을 수 있는 상태 값
    • key: location 객체의 고유 값, 초기에는 default 이며 페이지가 변경될때마다 고유의 값이 생성됨
  • useMatch
    • 현재 위치를 기준으로 주어진 경로의 경로에 대한 일치 데이터를 반환한다.
  • useNavigate
    • 예를 들어 onSubmit에서 submit 된 후 navigate(이동, 탐색)할 수 있는 함수를 반환한다.
    • useNavigate는 양식이 제출되거나 특정 event가 발생할 때, url을 조작할 수 있는 interface를 제공한다.
    • replace: true 일 경우 새 항목을 추가하는 대신 history stack의 현재 항목을 대체한다.
  • useNavigationType
    • 현재 navigate 유형 또는 사용자가 현재 페이지에 어떻게 왔는지를 반환한다. history stack 에 대한 pop, push 또는 교체 작업을 통해
    • navigate("../success", { replace: true});
    • 두 번째 인자로 { replace, state } 인수를 사용한다.
    • replace: true
    • navigate에 적힌 주소로 넘어간 후 뒤로가기를 하더라도 방금의 페이지로 돌아오지 않는다. 이 때는 자신의 메인 페이지 ("/")로 돌아오게 됩니다
  • navigate( '/이동경로', { state: { 키: 값, 키: 값, ... } } )
  • useOutlet
    • 내부적으로 <Outlet> 자식 경로를 렌더링하는 데 사용된다.
  • useOutletContext
  • useParams
    • <Route path>와 매치되는 현재 URL에서 동적 매개변수의 키/값 쌍의 개체를 반환한다.
import * as React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';

function ProfilePage() {
  // Get the userId param from the URL.
  let { userId } = useParams();
  // ...
}

function App() {
  return (
    <Routes>
      <Route path="users">
        <Route path=":userId" element={<ProfilePage />} />
        <Route path="me" element={...} />
      </Route>
    </Routes>
  );
}
  • useResolvedPath
    • This hook resolves the pathname of the location in the given to value against the pathname of the current location.
  • useRoutes
    • <Routes>와 기능적으로 동일하지만 js 개체를 사용하여 경로를 정의한다.
    • 반환 값은 경로 트리를 렌더링하는 데 사용할 수 있는 유효한 React 요소이거나 일치하는 항목이 없는 경우의 null 이다.
  • useSearchParams
    • 현재 위치에 대한 URL의 쿼리 문자열을 읽고 수정하는 데 사용된다.
    • React의 자체 useState hook처럼 useSearchParams는 현재 위치의 검색 매개 변수와 이를 업데이트하는 데 사용할 수 있는 두 가지 값의 배열을 반환한다.
    • useSearchParams를 통해서 쿼리스트링을 쉽게 파싱할 수 있다.(키, 값이 여러개인 경우 분리시키기 쉬워졌다.)
import \* as React from "react";  
import```js
import * as React from "react";
import { useSearchParams } from "react-router-dom";

function App() {
  let [searchParams, setSearchParams] = useSearchParams();

  function handleSubmit(event) {
    event.preventDefault();
    // The serialize function here would be responsible for
    // creating an object of { key: value } pairs from the
    // fields in the form that make up the query.
    let params = serializeFormQuery(event.target);
    setSearchParams(params);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>{/* ... */}</form>
    </div>
  );
}

Utilities

  • createRoutesFromChillden
  • createSearchParams
  • generatePath
  • Location
  • matchPath
  • matchRoutes
  • renderMatches
  • resolvePath