라우터 컴포넌트 props

2021. 10. 22. 16:32React/문법

- 파라미터: /profiles/velopert

- 쿼리: /about?details=true

 

1. match : Route 컴포넌트에서 연결하는 컴포넌트로 넘겨지는 정보로, 파라미터를 얻기 위해서는 match.params를 이용

const Profile = ({ match }) => {
  // 파라미터를 받아올 땐 match 안에 들어있는 params 값을 참조합니다.
  const { username } = match.params;
  const profile = profileData[username];
  if (!profile) {
    return <div>존재하지 않는 유저입니다.</div>;
  }
  return (
    <div>
      <h3>
        {username}({profile.name})
      </h3>
      <p>{profile.description}</p>
    </div>
  );
};
const App = () => {
  return (
    <div>
      <ul>
        <li>
          <Link to="/">홈</Link>
        </li>
        <li>
          <Link to="/about">소개</Link>
        </li>
      </ul>
      <hr />
      <Route path="/" exact={true} component={Home} />
      <Route path="/about" component={About} />
      <Route path="/profiles/:username" component={Profile} />
    </div>
  );
};

2. location :  라우트 컴포넌트에게 props 전달되는 location 객체에 있는 search 값에서 읽어올 수 있습니다.(string으로 제공되기 때문에 객체 변환이 필요)

cf> location 객체

{ key: 'ac3df4', // not with HashHistory!

  pathname: '/somewhere'

  search: '?some=search-string',

  hash: '#howdy',

  state: { [userDefined]: true } }

const About = ({ location }) => {
  const query = qs.parse(location.search, {
    ignoreQueryPrefix: true
  });
  const detail = query.detail === 'true'; // 쿼리의 파싱결과값은 문자열입니다.

  return (
    <div>
      <h1>소개</h1>
      <p>이 프로젝트는 리액트 라우터 기초를 실습해보는 예제 프로젝트랍니다.</p>
      {detail && <p>추가적인 정보가 어쩌고 저쩌고..</p>}
    </div>
  );
};

 

3. history : 라우트로 사용된 컴포넌트에게 match, location 과 함께 전달되는 props 중 하나, 이 객체를 통하여, 우리가 컴포넌트 내에 구현하는 메소드에서 라우터에 직접 접근을 할 수 있습니다 - 뒤로가기, 특정 경로로 이동, 이탈 방지 등..

function HistorySample({ history }) {
  const goBack = () => {
    history.goBack();
  };

  const goHome = () => {
    history.push('/');
  };

  useEffect(() => {
    console.log(history);
    const unblock = history.block('정말 떠나실건가요?');
    return () => {
      unblock();
    };
  }, [history]);

  return (
    <div>
      <button onClick={goBack}>뒤로가기</button>
      <button onClick={goHome}>홈으로</button>
    </div>
  );
}

 

 

- withRouter HoC : 라우트 컴포넌트가 아닌곳에서 match / location / history 를 사용해야 할 때 쓰면 됩니다.

const WithRouterSample = ({ location, match, history }) => {
  return (
    <div>
      <h4>location</h4>
      <textarea value={JSON.stringify(location, null, 2)} readOnly />
      <h4>match</h4>
      <textarea value={JSON.stringify(match, null, 2)} readOnly />
      <button onClick={() => history.push('/')}>홈으로</button>
    </div>
  );
};

export default withRouter(WithRouterSample); // withRouter HOC으로 컴포넌트 감싸서 export
const Profiles = () => {
  return (
    <div>
      ...

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

 

 

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

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

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

'React > 문법' 카테고리의 다른 글

Spread 연산자 사용 차이점  (0) 2022.01.10
SPA(Single Page Application)  (0) 2021.10.22
Router 라이브러리  (0) 2021.10.22
API 연동 - Context 사용  (0) 2021.10.22
API 연동 - 커스텀 Hook or 라이브러리 이용  (0) 2021.10.22