import React, { useState, useEffect } from "react";
const useConfirm = (message = "", callback) => {
if(typeof callback !== "function"){
return ;
}
const confirmed = () => {
if(confirm(message)){
callback()
}
};
return confirmed;
};
const App1 = () => {
const destroyWorld = () => console.log('it is gone, never come')
const res = useConfirm('Are you sure?', destroyWorld)
return (
<div>
<button onClick = {res}> Delete the World </button>
</div>
);
};
export default App1;
confirm은 window.confirm 이라고 하는 브라우저의 메소드
MDN Window.confirm() 참고
그래서 이 메소드를 이용하여 확인하는 모달창을 띄우는 함수를 생성.
App1 함수 스코프 밖에서 틀과 같은 함수를 만들고, App1 함수 내에서 실사용 할 수 있게 함. 확실히 클래스 컴포넌트일 때보다 간단할 것 같기는 함.
import React, { useState, useEffect } from "react";
const usePreventLeave = () => {
const listener = (event) => {
event.preventDefault();
event.returnValue = "";
}
const enablePrevent = () => {
window.addEventListener('beforeunload', listener)
};
const disablePrevent = () => {
window.removeEventListener('beforeunload', listener)
};
}
const App1 = () => {
const {enablePrevent, disablePrevent } = usePreventLeave()
return (
<div>
<button onClick={enablePrevent}>protect</button>
<button onClick={disablePrevent}>unprotect</button>
</div>
);
}
export default App1;
여기서 beforeunload 이벤트는 문서와 그 리소스가 언로드 되기 직전에 window에서 발생한다.
참고자료 MDN window: beforeunload event