Example of useOnClickOutside() Custom Hook in React.js

Example of useOnClickOutside() Custom Hook in React.js

Here's how to make a useOnClickOutside() hook in React to notice clicks outside a certain element:

import { useEffect } from 'react';

const useOnClickOutside = (ref, handler) => {
  useEffect(() => {
    const listener = (event) => {
      // Do nothing if clicking ref's element or descendent elements
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }
      // Call the handler function when clicking outside the ref's element
      handler(event);
    };

    // Add event listener for "mousedown" event
    document.addEventListener('mousedown', listener);

    // Cleanup function to remove event listener
    return () => {
      document.removeEventListener('mousedown', listener);
    };
  }, [ref, handler]);
};

export default useOnClickOutside;

This useOnClickOutside hook takes two arguments:

  1. ref: A ref to the element you want to detect clicks outside of.

  2. handler: A callback function to be called when a click outside the element is detected.

You can use this hook in your components to notice when someone clicks outside a certain element. Here's how to use it:

import React, { useRef } from 'react';
import useOnClickOutside from './useOnClickOutside'; // Assuming you've placed the hook in a separate file

const MyComponent = () => {
  const ref = useRef(null);

  // Handle click outside by setting state
  const handleClickOutside = () => {
    console.log('Clicked outside!');
  };

  // Attach useOnClickOutside hook to the ref
  useOnClickOutside(ref, handleClickOutside);

  return (
    <div>
      <h1>Click Outside Example</h1>
      <div ref={ref} style={{ width: '200px', height: '200px', background: 'lightblue' }}>
        Click inside this box
      </div>
    </div>
  );
};

export default MyComponent;

In this example:

  • We define the MyComponent functional component.

  • We create a ref using the useRef hook and attach it to a div.

  • We define a handleClickOutside function that logs a message to the console when called.

  • We use the useOnClickOutside hook to detect clicks outside the div element and call the handleClickOutside function.

  • When a click occurs outside the div, the message "Clicked outside!" will be logged to the console.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!