Home > Software design >  React (Next.js) hook useOutsideClick cancels my links
React (Next.js) hook useOutsideClick cancels my links

Time:04-30

i'm using the following hook to handle "click away" feature to show/hide a dropdown:

const useOutsideClick = (ref: NonNullable<RefObject<HTMLButtonElement>>) => {
  const [outsideClick, setOutsideClick] = useState<boolean | null>(null)

  useEffect(() => {
    const handleClickOutside = (e: React.MouseEvent | Event) => {
      if (
        ref &&
        !(ref?.current as unknown as RequiredCurrentRef).contains(
          e?.target as Node
        )
      ) {
        setOutsideClick(true)
      } else {
        setOutsideClick(false)
      }

      setOutsideClick(null)
    }

    document.addEventListener('mousedown', handleClickOutside)

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

  return outsideClick
}
export default useOutsideClick

the hook works fine but once i click on <a href> links (separated component from the dropdown) it does not redirect, so links don't work how do i solve this?

Edit i'm using bulma.css for dropdowns

CodePudding user response:

I think you dont need to create an extra hook at all.

If you want do du something if the user clicks on or out of the element you can use the onBlur and onFocus callbacks.

If you want to blur it for some other reason (like on the click of a button) you can use the reference of the anchor and call the blur() method whenever you like.

  • Related