티스토리 뷰

반응형

export 'withRouter' (imported as 'withRouter') was not found in 'react-router-dom'

위의 애러가 난다면, router에서 history를 사용하기위해 설정 도중에 에러가 떴을 것이다. 만약 아래와 같이 실행을 했는데 안된다면, 나와 같은 이유에서 안되는 것이기 때문에 해결책을 참고하자.

 

 

1. history를 쓰려면  아래와 같이 import를 한다.

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

 

 

2. 아래와 같이 export를 한다.

export default withRouter(App);

 

 

3. 사용하고자 하는 컴포넌트에서 history를 props로 받아서 사용한다.

import React from "react";

const TeamInfo = ({ history }) => {
    const goBack = () => {
        history.goBack();
      };
      const goHome = () => {
        history.push("/");
      };
      const replaceToHome = () => {
        history.replace("/");
      };

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

export default TeamInfo;

 

그러면 안된다. 이러한 방식으로 app.jsx에 추가를 해주면 props로 history관리를 하는 방식은 react router v5에서만 가능했다. 그리고 아래와 같이 history를 사용하는 것도 당연히 안 된다. 

 

 

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

...


    const history = useHistory();
    const goBack = () => {
        history.goBack();
      };
      const goHome = () => {
        history.push("/");
      };
      
...

 

 

따라서 버전을 내리거나, 아래의 url에서 v6관련 문서를 확인하자.

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함