Frontend/React
2021-05-03 :: 리액트 라우터로 SPA 개발하기3
셩이22
2021. 5. 3. 18:42
withRouter
withRouter 함수는 HoC(higher-order Component)이다. 라우트로 사용된 컴포넌트가 아니어도 match, location, history 객체를 접근할 수 있게 해 준다.
import React from 'react';
import {withRouter} from 'react-router-dom';
const WithRouterSample = ({location, match, history}) => {
return(
<div>
<h4>location</h4>
<textarea
value={JSON.stringify(location, null, 2)}
rows={7}
readOnly
/>
<h4>match</h4>
<textarea
value={JSON.stringify(match, null, 2)}
rows={7}
readOnly
/>
<button onClick={()=>history.push('/')}>홈으로</button>
</div>
);
}
export default withRouter(WithRouterSample);
JSON.stringify의 두 번째 파라미터와 세 번째 파라미터를 위와 같이 null, 2로 설정해 주면 JSON에 들여쓰기가 적용된 상태로 문자열이 만들어진다.