The task is to create a useClickOutside() hook that dismisses a dropdown menu when a click is made outside of the dropdown. The boilerplate code:
// This is a React coding question from BFE.dev
import React from 'react'
export function useClickOutside(callback: () => void) {
// your code here
}
// to try your code on the right panel
// export App() component like below
// export function App() {
// return <div>your app</div>
// }
First step is to create a ref for the element to be clicked
const ref = useRef<T>(null)
A function to handle when a click is made is created after the ref is set. The function checks where the mouse is when the click is made, then calls the callback function
const handleClick = (e: MouseEvent) {
if(ref.current && !ref.current.contains(e.target as Node)) {
callback()
}
}
An event listener is then added to listen for a click
document.addEventListener("mousedown", handleClick)
The event listener is removed when the component is unmounted.
document.removeEventListener("mousedown", handleClick)
The final code looks like this:
// This is a React coding question from BFE.dev
import React, { useRef, useEffect } from 'react'
export function useClickOutside<T extends HTMLElement>(callback: () => void) {
// your code here
const ref = useRef<T>(null)
useEffect(() => {
const handleClick = (e: MouseEvent) => {
if(ref.current && !ref.current.contains(e.target as Node)) {
callback()
}
}
document.addEventListener('mousedown', handleClick)
return () => {
document.removeEventListener('mousedown', handleClick)
}
}, [callback])
return ref;
}
// to try your code on the right panel
// export App() component like below
// export function App() {
// return <div>your app</div>
// }
That's all folks!
Top comments (0)