※ 강의를 듣고 제가 이해한 내용을 바탕으로 정리한 것이라서 오류가 있을 수 있습니다.

 

useReactRouter Hook 사용하기

지난 포스트에서 withRouter 라는 함수를 사용해서 라우트로 사용되고 있지 않은 컴포넌트에서도 라우트 관련 props 인 match, history, location 을 조회하는 방법을 확인해보았다.

withRouter 를 사용하는 대신에 Hook 을 사용해서 구현을 할 수도 있는데 아직은 리액트 라우터에서 공식적인 Hook 지원은 되고 있지 않다 (될 예정).

그 전까지는 라이브러리를 설치해서 Hook 을 사용하여 구현을 할 수 있다.

 

설치

npm install use-react-router

 

그 다음에 RouterHookSample.js 라는 파일을 생성 후 다음 코드를 작성

RouterHookSample.js

import useReactRouter from 'use-react-router';

function RouterHookSample() {
  const { history, location, match } = useReactRouter;
  console.log({ history, location, match });
  return null;
}

export default RouterHookSample;

제 이 컴포넌트를 Profiles 컴포넌트에서 WithRouterSample 밑에 렌더링 한다.

Profiles.js

import React from 'react';
import { Route, NavLink } from 'react-router-dom';
import Profile from './Profile';
import WithRouterSample from './WithRouterSample';
import RouterHookSample from './RouterHookSample';

const Profiles = () => {
  return (
    <div>
      <h3>유저 목록:</h3>
      <ul>
        <li>
          <NavLink
            to="/profiles/kim"
            activeStyle={{ background: 'black', color: 'white' }}
          >
            kim
          </NavLink>
        </li>
        <li>
          <NavLink
            to="/profiles/gildong"
            activeStyle={{ background: 'black', color: 'white' }}
          >
            gildong
          </NavLink>
        </li>
      </ul>

      <Route
        path="/profiles"
        exact
        render={() => <div>유저를 선택해주세요.</div>}
      />
      <Route path="/profiles/:username" component={Profile} />
      <WithRouterSample />
      <RouterHookSample />
    </div>
  );
};

export default Profiles;

 

실행 결과

+ Recent posts