상현에 하루하루
개발자의 하루

해당컴포넌트 outside 영역 클릭 이벤트

( 업데이트: )

🤔 무엇을

구현하고싶은 것은 Modal 을 구현하고싶다. 모달팝업이 띄워졌을때 바깥 영역을 클릭 하였을 때 이벤트를 발생시켜서 모달팝업의 상태를 close 로 변경하고싶다. 바깥 영역을 클릭 이벤트를 구현하는 방법은?

🔑 해결

import React, { useRef, useEffect } from "react";

/**
 * Hook that alerts clicks outside of the passed ref
 */
function useOutsideAlerter(ref) {
  /**
   * Alert if clicked on outside of element
   */
  function handleClickOutside(event) {
    if (ref.current && !ref.current.contains(event.target)) {
      alert("You clicked outside of me!");
    }
  }

  useEffect(() => {
    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  });
}

/**
 * Component that alerts if you click outside of it
 */
export default function OutsideAlerter(props) {
  const wrapperRef = useRef(null);
  useOutsideAlerter(wrapperRef);

  return <div ref={wrapperRef}>{props.children}</div>;
}Code language: JavaScript (javascript)

클릭해도 이벤트가 발생하지 않을 element를 선택해서 해당 element가 아닌 곳을 클릭했을때 documen 전체에 이벤트를 등록해서 지정한 element 이외의 영역을 클릭했을때 이벤트 발생! 해당 이벤트에다 내가 적용할 코드를 작성하면 된다. 이렇게 해결하였다.