프로젝트를 진행하면서 모달을 만들고, 그 모달의 바깥을 누르면 자동으로 닫히게 하는걸 개발했다.
return modal.isOpen ? (
<S.ModalBackground onClick={closeModal}>
<S.ModalContainer>
{/* 텍스트 부분 */}
<S.ModalTextWrapper>
<S.ModalTextTitle>{modal.title}</S.ModalTextTitle>
<S.ModalTextInfo>
<S.ModalTextContent>{modal.content}</S.ModalTextContent>
<S.ModalTextSubContent>{modal.sub}</S.ModalTextSubContent>
</S.ModalTextInfo>
</S.ModalTextWrapper>
...
이런식으로 !
그런데 모달부분을 눌러도 그냥 closeModal이 실행되어 닫히는게 아닌가 ...
이게 무슨 어이없는 일이지 !! 하고 찾아봤는데
음 .. 당연한거였다. (사실 좀만 생각해봐도 당연함)
상위에 onClick 이벤트가 있기 때문 ..
그래서 필요한건
onClick={(e) => e.stopPropagation()} 이다.
이벤트가 상위 요소로 전파되지 않도록 방지한다.
<S.ModalBackground onClick={closeModal}>
<S.ModalContainer onClick={(e) => e.stopPropagation()}>
{/* 텍스트 부분 */}
...
이런식으로 되는데, 모달 창 내부의 클릭 이벤트가 모달 배경(S.ModalBackground)이나 다른 상위 요소로 전파되지 않도록 하는 것이다.
또 있다. e.preventDefault()다.
이벤트의 기본 동작을 취소한다. 예를 들어, 링크 클릭 시 페이지 이동을 방지하거나 폼 제출 시 페이지 리로드를 막는 데 사용된다.