...
/Improving User Interactivity Using the useClickOutside Hooks
Improving User Interactivity Using the useClickOutside Hooks
Learn about the useClickOutside custom hook that is designed to detect clicks outside a specific component of the layout.
Introduction to the useClickOutside
hooks
In the internal implementation of the useClickOutside
custom hook, the React useEffect
hook is utilized.
In the Global Event Handling and Interactive UI lesson, we learned about a case where we can detect when a user clicks outside a component. This feature is pretty generic, and we want to take advantage of this in various parts of the project, such as dismissing a modal or tooltip—see the image below.
Press + to interact
Implement the useClickOutside
hook
Let's see if we can refactor the old code a bit and turn it into a custom useClickOutside
hook:
// Custom hook to detect clicks outside a specified ref elementfunction useClickOutside(ref, handler) {useEffect(() => {const clickHandler = e => {if (!ref.current) return;if (!ref.current.contains(e.target)) {handler && handler();}};// Add event listener for mousedown eventswindow.addEventListener("mousedown", clickHandler);// Cleanup function to remove event listener when the component unmounts or when 'ref' or 'handler' changesreturn () => {window.removeEventListener("mousedown", clickHandler);};}, [ref, handler]);}
Detect clicks outside a specified ref element using custom hook
...