본문 바로가기
FrontEnd

React Class 컴포넌트에서 navigate 동작 방법

by E_van 2022. 11. 10.

먼저 withRouter.js 라는 이름의 Hook을 생성 후 아래와 같은 내용을 입력해준다.

import * as React from "react"
import {useNavigate} from 'react-router-dom';

export const withRouter = (Component) => {
    const Wrapper = (props) => {
        const navigate = useNavigate();

        return (
            <Component
                navigate={navigate}
                {...props}
            />
        );
    };

    return Wrapper;
};

그 후 Class 컴포넌트 파일 안에서
아래와 같이  props의 navigate에 이동하고자 하는 페이지를 넣고 Class 컴포넌트를 withRouter로 감싸주면 된다.

this.props.navigate('/login');
export default withRouter(FindPassword);