개발자의 길

React dom v6 브라우저 뒤로가기 시에 특정 액션 하기 본문

16. REACT

React dom v6 브라우저 뒤로가기 시에 특정 액션 하기

자르르 2022. 9. 6. 13:09


react 에서, 특정 컴포넌트를 페이지 이동이 아닌, 모달 팝업(레이어 팝업) 같이 열었을 경우,

 

뒤로 가기 클릭스, 해당 팝업만 닫고 싶은데, 페이지가 뒤로 가기 되 버려서 당황 스러웠다.

 

그럴 경우, 뒤로 가기 이벤트를 잡아서, 다른 액션을 주었다.

 

function closeView() {
	//여기에, 뒤로 가기 클릭시 할 액션을 정의 하면 된다. 나는 레이어팝업을 닫는 액션을 했다.
    props.onClose();
}

useEffect(() => {
    const randomKey = 페이지의 특정한 값을 부여해주세요.
    // 별도로 history에 특정값을 주었다.
    window.history.pushState('fake-route'+randomKey, document.title, window.location.href);

    addEventListener('popstate', closeView);

    // Here is the cleanup when this component unmounts
    return () => {
        removeEventListener('popstate', closeView);
        // If we left without using the back button, aka by using a button on the page, we need to clear out that fake history event
        if (window.history.state === 'fake-route'+randomKey) {
            window.history.back();
        }
    };

}, []);

 

쪼금 보완해서 사용하면 된다.

'16. REACT' 카테고리의 다른 글

[React] 스크롤 바닥 (아래) 더보기 액션  (0) 2022.09.21


이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
공유하기 링크
Comments