Java Scripts/React.js

Hook in React - usePreventLeave

HobbyCoding 2023. 10. 7. 07:06
728x90

note) browser window 를 빠져나가려 할 때 저장하지 않았다고 알려주는 기능.


note) "beforeunload" event 에 등록된 함수는 browser window 가 빠져나갈 때 호출된다. 


note) protect button 을 누르고 window 를 빠져나가면 “Changes you made may not be saved.”  의 pop up message 가 나타나고, Unprotected button 을 누르고 window 를 빠져나가면 아무런 message 가 보이지 않는다. 

 

 

export const usePreventLeave = () => {
  const listener = event => {
    event.preventDefault();
    event.returnValue = "";
  };
  const enablePrevent = () => window.addEventListener("beforeunload", listener);
  const disablePrevent = () =>
    window.removeEventListener("beforeunload", listener);
  return { enablePrevent, disablePrevent };
};

export default function App() {
  const { enablePrevent, disablePrevent } = usePreventLeave();
  return (
    <div className="App">
      <button onClick={enablePrevent}>Protect</button>
      <button onClick={disablePrevent}>Unprotect</button>
    </div>
  );
}

 

note) 위는 아래의 교육과장을 이수하면서 정리한 것이다.

https://nomadcoders.co/react-hooks-introduction/lobby?utm_source=free_course&utm_campaign=react-hooks-introduction&utm_medium=site