개인공부/TIL(Today I Learned)

TIL 74일차_React Router : withRouter

soon327 2021. 4. 2. 05:00

What is withRouter ?

withRouterRouter가 아닌 컴포넌트에 Router 특성을 부여한다.
Router는 location, match, history를 사용한다.

location

location 객체에는 현재 페이지의 정보가 들어간다.

pathname: 현재 페이지의 경로명
search: 현재 페이지의 query String
hash: 현재 페이지의 Hasy

match

<Route path>와 URL이 매칭한 정보가 담겨있다.

path : 라우터에 정의된 path
url : 실제 클라이언트로 부터 요청된 url path
isExact : true일 경우 전체 경로가 완전히 매칭될 경우에만 요청을 실행
params : url path로 전달된 파라미터 객체

history

브라우저의 history와 유사하며, 스택에 현재까지 이동한 url의 경로들이 담겨있는 형태로 주소를 임의로 변경하거나 되돌아갈 수 있다.

length : 전체 스택의 길이
action : 최근 수행된 action
push : 새로운 경로를 history로 푸시하여 페이지 이동
goBack() : 이전 페이지로 이동
goForward() : 앞 페이지로 이동

withRouter 사용하기

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

export default withRouter();

특정 컴포넌트가 라우터처럼 쓰이길 원한다면,
위처럼 withRouter로 감싸고 withRouter를 반환해야한다.

예시

import React from "react";
import { Link, withRouter } from "react-router-dom";
import styled from 'styled-components'

export default withRouter(({location : {pathname}}) => (

  <header>
    <ul>
      <li>
        <SLink current={pathname ==='/'} to="/">Home</SLink>
      </li>
      <li>
        <SLink current={pathname === '/user'} to="/user">User</SLink>
      </li>
      <li current={pathname === '/coins'}>
        <SLink current={pathname === '/item'} to="/item">Item</SLink>
      </li>
    </ul>
  </header>
)
)

const SLink = styled(Link)`
    color: ${props => props.current? 'white' : 'black'};
    background-color: ${props => props.current? 'yellow' : 'transparent'}
  `

link를 클릭하여 url이 /user이 되면 location.pathname/user가 되고,
current prop이 true가 되어, 원하는 스타일을 적용해줄 수 있다.

참고: Wonit

'개인공부 > TIL(Today I Learned)' 카테고리의 다른 글

TIL 76일차_redux:basic  (0) 2021.04.04
TIL 75일차_구조분해할당,object,axios : basic  (0) 2021.04.03
TIL 73일차_React Router  (0) 2021.04.01
TIL 72일차_React hook : basic  (0) 2021.03.31
TIL 71일차_ Why React Hook?  (0) 2021.03.30