[React] esc로 modal, alert 닫기

yes·2022년 2월 22일
1

React

목록 보기
2/8

modal이랑 alert같은 것들이 뜨면 유저들은 esc로 없애고 싶어 한다고 생각해서 hooks를 만들어보았다.

✨useKeyEscClose

// useKeyEscClose.js
export const useKeyEscClose = (closeThing) => {
    useEffect(() => {
        const escKeyModalClose = (e) => {
            if (e.keyCode === 27) {
                closeThing();
            }
        };
        window.addEventListener("keydown", escKeyModalClose);
        return () => window.removeEventListener("keydown", escKeyModalClose);
    }, []);
};

이 hooks은 인자로 closeThing이라는 esc Key를 누를 때 발생하는 닫는 함수가 들어간다.
ex)

const closeThing = () => {
	setIsModalOpen(false)
}

keydown event가 발생하면 keycode를 검사하여 closeThing 함수를 실행시켜준다.
여기서 keycode는 본인의 입맛에 맞게 설정하면 된다.😋

🎈참고자료
https://stackoverflow.com/questions/1481626/how-to-handle-esc-keydown-on-javascript-popup-window

2개의 댓글

comment-user-thumbnail
2022년 2월 22일

잘 보고 갑니다! 많은 도움이 됬어요!

답글 달기
comment-user-thumbnail
2022년 11월 18일

감사합니다!!!!!!!!!!!!

답글 달기