Skip to content

Instantly share code, notes, and snippets.

@Aulos
Forked from gragland/use-onclick-outside-example.jsx
Last active November 6, 2018 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aulos/5ad4d9f5d030ac857f57125e7a407d99 to your computer and use it in GitHub Desktop.
Save Aulos/5ad4d9f5d030ac857f57125e7a407d99 to your computer and use it in GitHub Desktop.
import { useState, useEffect, useRef } from 'react';
// Usage
function App() {
// Create a ref that we add to the element for which we want to detect outside clicks
// State for our modal
const [isModalOpen, setModalOpen] = useState(false);
// Call hook passing in the ref and a function to call on outside click
const ref = useOnClickOutside(() => setModalOpen(false));
return (
<div>
{isModalOpen ? (
<div ref={ref}>
👋 Hey, I'm a modal. Click anywhere outside of me to close.
</div>
) : (
<button onClick={() => setModalOpen(true)}>Open Modal</button>
)}
</div>
);
}
// Hook
function useOnClickOutside(handler) {
const ref = useRef();
useEffect(() => {
const listener = event => {
// Do nothing if clicking ref's element or descendent elements
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
}, []); // Empty array ensures that effect is only run on mount and unmount
return ref;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment