React
리액트 - 함수형 프로그래밍 useConfirm
rhanziy
2022. 5. 18. 00:12
const useConfirm = (message = "", onConfirm, onCancel) => {
if ( !onConfirm && typeof onConfirm !== "function") {
return;
}
if ( onCancel && typeof onCancel !== "function") {
return;
}
const confirmAction = () => {
if (window.confirm(message)) {
onConfirm();
} else {
onCancel();
}
};
return confirmAction;
};
export default function App() {
const deleteWorld = () => console.log("Deleting the world");
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>
);
}
버튼을 누르면 사용자의 이벤트에 따라 결과 값이 다른 콘솔찍는 코드.
함수형 컴포넌트를 만들어서 모듈화하고 파라미터로 전달된 값을 통해 기능 구현하기.
많이 연습해서 자유자재로 쓸 수 있길 ㅠㅠ
useState와 useEffect를 사용하지않아서 훅이라고 볼 순 없지만! 이런 기본뼈대에 리액트에서 제공하는
여러가지 훅을 조립해서 페이지를 만들어보자.