DEV Community

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

Posted on

2 1 1 1 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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series