DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 20

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>
// }

Enter fullscreen mode Exit fullscreen mode

First step is to create a ref for the element to be clicked

const ref = useRef<T>(null)
Enter fullscreen mode Exit fullscreen mode

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()
}
}
Enter fullscreen mode Exit fullscreen mode

An event listener is then added to listen for a click

document.addEventListener("mousedown", handleClick)
Enter fullscreen mode Exit fullscreen mode

The event listener is removed when the component is unmounted.

document.removeEventListener("mousedown", handleClick)
Enter fullscreen mode Exit fullscreen mode

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>
// }

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)