Java Scripts/React.js
Hook in React - useConfirm
HobbyCoding
2023. 9. 28. 13:37
728x90
note) useEffect 나 useState 를 사용하지 않는 sample 임.
note) onClick 이 실행되면 confirmDelete 이 실행되는데, confirmDelete은 useConfirm에서 return 된 confirmAction 이다
export const useConfirm = (message = "", onConfirm, onCancel) => {
if (!onConfirm || typeof onConfirm !== "function") {
return;
}
if (onCancel && typeof onCancel !== "function") { // onCancel is not mandatory argument
return;
}
const confirmAction = () => {
if (confirm(message)) {
onConfirm(); // if click "yes" button
} else {
onCancel(); // if click "no" button
}
};
return confirmAction;
};
export default function App() {
const deleteWorld = () => console.log("Deleting the wordl")
const abort = () => console.log("Aborted")
const confirmDelete = useConfirm("Are you sure", deleteWorld, abort)
return (
<div className="App">
<button onClick={confirmDelete}>Delete the world</button>
</div>
);
}
note) 위는 아래의 교육과장을 이수하면서 정리한 것이다.