티스토리 뷰

front-end/react

[React] react router

kmj24 2021. 6. 4. 02:50

Router란?

라우터는 컴퓨터 네트워크에서 데이터를 송수신하는 장치이다.

패킷의 위치를 추출하여 그 위치에 대한 최적의 경로(가장 빠르게 동신이 가능한 경로)를 지정하며 이 경로를 따라 데이터 패킷을 다음 장치로 전향시키는 네트워크 중계 장치이다.

router 마크

사실 Router는 여기서 기술할 react router와는 관련이 없다. 

하지만 "경로를 설정한다"라는 기능은 동일하다.

 

React router

React router는 설정한 URL에 따라 콘텐츠를 전송해준다.

react-router는 서드파티 라이브러리로써, 컴포넌트를 routing하기위해 가장 많이 사용하는 라이브러리이다.

react router 공식 문서 소개 페이지

router를 직접 구현하는 것은 시간이 걸리는 작업이다.

react router 라이브러리를 사용하면 이러한 작업을 간단하게 해결해 줄 수 있다.

 

여기서는 라우팅을 담당하는데 가장 많이 사용되는 BrouserRouter, Switch, Route에 대하여 포스팅 할것이다.(그 외 HashRouter, Redirect, MemoryRouter등 다양한 기능이 있다.)

우선 react-router-dom 라이브러리를 프로젝트에 설치한다.

npm install react-router-dom @types/react-router-dom --save

react router를 사용하여 url에 따라 컴포넌트를 지정
localhost:3000/coin_api 컴포넌트로 들어왔다.

 

React의  Router설정을 다음과 같이 했다.

여기서 설정한 코드의 내용을 살펴보자.

<BrowserRouter>
  <Switch>
    <Route path="/" exact component={Default}/>
    <Route path="/coin_api" exact component={CoinAPI}/>
  </Switch>
</BrowserRouter>

 

BrowserRouter

BrowserRouter를 따라 들어가보면

export interface BrowserRouterProps {
    basename?: string;
    getUserConfirmation?: (message: string, callback: (ok: boolean) => void) => void;
    forceRefresh?: boolean;
    keyLength?: number;
}
export class BrowserRouter extends React.Component<BrowserRouterProps, any> {}

요런 형태이다.

React.Component에 BrowserRouterProps, any를 제너릭으로 넘겨준것을 상속받는다.

즉 React.Component이다.

공식 문서의 설명은 다음과 같다.

A <Router> that uses the HTML5 history API (pushState, replaceState and the popstate event) 
to keep your UI in sync with the URL.
 -> HTML5 history API를 사용하여 UI과 URL을 동기화 하는 Router이다.

BrowserRouterProps를 살펴보자

모든 요소는 nullable이다.

basename

 - 문자열 타입이다.

 - react app의 기본 경로를 지정한다.

<BrowserRouter basename="/base_url">
</BrowserRouter>

getUserCofirmation

 - 함수 타입이다.

 - window.confirm을 활용하여 navigation을 확인하는데 사용한다. 

<BrowserRouter getUserConfirmation={(message, callback) => {
   const allowTransition = window.confirm(message);
   callback(allowTransition);
}}>

keyLength

 - number타입이다.

 - location.key의 길이를 지정하며 기본값은 6이다.

 

children

 - ReactNode 타입이다.

 - 렌더링 할 하위 요소를 설정한다.

 - react 16버전 이후에는 단일 하위 요소를 사용한다.

 

Switch

Route로 설정된 자식 컴포넌트 중 매칭되는 첫번째 Route를 렌더링한다.

다음의 코드가 있다.

<BrowserRouter>
  <Route path="/" exact component={Default}/>
  <Route path="/coin_api" exact component={CoinAPI}/>
  <Route path="/coin_api" exact component={Default}/>
</BrowserRouter>

여기서 만약 /coin_api로 접속한다면 Default컴포넌트와 CoinAPI컴포넌트가 모두 렌더링 된다.

하지만 Switch로 Route를 감싼다면 위의 코드에서 첫번째로 매칭되는 CoinAPI 컴포넌트만 렌더링 하게 된다.

 

Route

props로 path에 경로를 설정하고 해당 경로에 맞는 컴포넌트를 렌더링 할 수 있도록 한다.

path를 "/coin_api"로 설정 한것은 "/coin_api"라는 경로로 이동하면 Default 컴포넌트가 렌더링 된다.

exact는 path에 설정한 경로를 정확히 매칭시키기 위함이다. 

component에는 path로 설정한 경로에 대한 렌더링할 컴포넌트를 지정한다.

 

 

참고 : https://reactrouter.com/

 

React Router: Declarative Routing for React

Learn once, Route Anywhere

reactrouter.com

https://velopert.com/3417

 

react-router :: 1장. 리액트 라우터 사용해보기 | VELOPERT.LOG

이 튜토리얼은 3개의 포스트로 나뉘어진 이어지는 강좌입니다. 목차를 확인하시려면 여기를 참고하세요. SPA 란? Single Page Application (싱글 페이지 어플리케이션) 의 약자입니다. 말 그대로, 페이지

velopert.com

 

'front-end > react' 카테고리의 다른 글

[React] react hooks와 closure의 관계  (0) 2021.06.23
Redux-saga로 웹 소켓 통신 구현  (0) 2021.06.13
Redux  (0) 2021.05.23
[React] props.history와 Redirect 차이?  (0) 2021.05.17
[React] Lifecycle과 useEffect hook  (0) 2021.04.30
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함