e.stopPropagation()& e.preventDefault()

오찬주·2025년 1월 30일

개발 log

목록 보기
11/23
post-thumbnail

프로젝트를 진행하면서 모달을 만들고, 그 모달의 바깥을 누르면 자동으로 닫히게 하는걸 개발했다.

 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 이벤트가 있기 때문 ..

e.stopPropagation()

그래서 필요한건

onClick={(e) => e.stopPropagation()} 이다.

이벤트가 상위 요소로 전파되지 않도록 방지한다.

 <S.ModalBackground onClick={closeModal}>
     <S.ModalContainer onClick={(e) => e.stopPropagation()}>
       {/* 텍스트 부분 */}
...

이런식으로 되는데, 모달 창 내부의 클릭 이벤트가 모달 배경(S.ModalBackground)이나 다른 상위 요소로 전파되지 않도록 하는 것이다.

그럼 다른 방법은 없나? -> e.preventDefault()

또 있다. e.preventDefault()다.

이벤트의 기본 동작을 취소한다. 예를 들어, 링크 클릭 시 페이지 이동을 방지하거나 폼 제출 시 페이지 리로드를 막는 데 사용된다.

profile
프론트엔드 엔지니어를 희망합니다 :-)

0개의 댓글