DEV Community

Cover image for Closing modals or dropdown on Outside click or scroll.
mmvergara
mmvergara

Posted on

1 1 1 2 1

Closing modals or dropdown on Outside click or scroll.

Ever built a modal or dropdown and struggled to figure out how to close it when the user clicks outside it? Yep..

Here's a cool react hook for you that can deal with that

import { useEffect, useRef } from "react";

const useOutsideClickOrScroll = <T extends HTMLElement>(
  callback: () => void
) => {
  const ref = useRef<T>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback();
      }
    };

    const handleScroll = () => {
      callback();
    };

    document.addEventListener("mousedown", handleClickOutside);
    window.addEventListener("scroll", handleScroll, true);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      window.removeEventListener("scroll", handleScroll, true);
    };
  }, [callback]);

  return ref;
};

export default useOutsideClickOrScroll;
Enter fullscreen mode Exit fullscreen mode

This hook uses useRef to target a DOM element and triggers a callback on outside clicks or scroll events, ensuring proper cleanup with useEffect. It returns the ref for easy attachment to any DOM element.

Here's a sample usage

import React, { useState } from "react";
import useOutsideClickOrScroll from "./useOutsideClickOrScroll";

const Dropdown = () => {
  const [isOpen, setIsOpen] = useState(false);

  const handleClose = () => {
    setIsOpen(false);
  };

  const ref = useOutsideClickOrScroll<HTMLDivElement>(handleClose);

  return (
    <div>
      <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
      {isOpen && (
        <div ref={ref}>
          <p>Dropdown Content</p>
        </div>
      )}
    </div>
  );
};

export default Dropdown;

Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay