[React] 외부 클릭 이벤트

게코젤리·2023년 2월 14일
0
function Header() {
  const [searchOpen, setSearchOpen] = useState(false);
  const searchRef = useRef(null);

  const useClickOutside = (
    ref: React.RefObject<HTMLElement>,
    onClickOutside: (e: React.MouseEvent) => void
  ) => {
    useEffect(() => {
      const handleClickOutside = (e: any) => {
        if (ref.current && !ref.current.contains(e.target)) {
          onClickOutside(e);
        }
      };
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }, [ref, onClickOutside]);
  };

  useClickOutside(searchRef, () => {
    if (!searchOpen) return;
    setSearchOpen((prev) => !prev);
  });

  const toggleSearch = () => {
    setSearchOpen((prev) => !prev);
  };
  return (
    <Nav>
      <Col>
        <Search ref={searchRef}>
          <svg onClick={toggleSearch}>
          </svg>
        </Search>
      </Col>
    </Nav>
  );
}

0개의 댓글