The source code for this library is available on GitHub.

Vaiva's Pattern Library.

useClickOutside Hook

Clicking outside a referential element will close it. This hook is useful for dropdowns, modals, etc. To use it you must import useRef and create a variable named 'wrapperRef' with a value of 'useRef(null)'. You then attach 'ref={wrapperRef} to the element you'd like the user to click outside of. To close the element, create a 'closeInput' function sets state to the desired value.


import { useEffect } from 'react';

const useClickOutside = (ref, closeInput) => {
  useEffect(() => {
    function handleClickOutside(e) {
      if (ref.current && !ref.current.contains(e.target)) {
        closeInput();
        // stopPropagation is optional -- remove if breaking
        e.stopPropagation();
      }
    }
    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [ref]);
};

export default useClickOutside;

More Components

TailwindCSS Text Carousel

The title speaks volumes.

Button

There is no description. Have a poem instead.

When I heard the learn’d astronomer,
When the proofs, the figures, were ranged in columns before me,
When I was shown the charts and diagrams, to add, divide, and measure them,
When I sitting heard the astronomer where he lectured with much applause in the lecture-room,
How soon unaccountable I became tired and sick,
Till rising and gliding out I wander’d off by myself,
In the mystical moist night-air, and from time to time,
Look’d up in perfect silence at the stars.