Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Handle click outside a component in react with hooks

import React, { useRef, useEffect } from "react";

/**
 * Hook that alerts clicks outside of the passed ref
 */
function useOutsideAlerter(ref) {
  useEffect(() => {
    /**
     * Alert if clicked on outside of element
     */
    function handleClickOutside(event) {
      if (ref.current && !ref.current.contains(event.target)) {
        alert("You clicked outside of me!");
      }
    }
    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref]);
}

/**
 * Component that alerts if you click outside of it
 */
export default function OutsideAlerter(props) {
  const wrapperRef = useRef(null);
  useOutsideAlerter(wrapperRef);

  return <div ref={wrapperRef}>{props.children}</div>;
}
Comment

outside click hook react

import { useEffect, MutableRefObject } from 'react'

export const useOutsideClick = <T extends Array<MutableRefObject<any>>>(
  ref: T,
  callback: () => void
): void => {
  useEffect(() => {
    const handler = (event: MouseEvent): void => {
      // Check if the mouse click was within the element's ref.

      if (!ref || ref.length === 0) return
      const node = ref.find((x) => x?.current?.contains(event?.target as Node))

      if (!node) {
        callback()
      }
    }

    window.addEventListener('mousedown', handler)

    return (): void => {
      window.removeEventListener('mousedown', handler)
    }
  }, [ref, callback])
}

// Usage (it should be in the component*)
const firstRef  = useRef(null)
const secondRef = useRef(null)
const handleClick = () => { console.log('Clicked outside ref') }

useOutsideClick([firstRef, secondRef], handleClick)
Comment

PREVIOUS NEXT
Code Example
Javascript :: create select option using jquery 
Javascript :: how to open print dialog box on button click 
Javascript :: How to send form data from react to express 
Javascript :: vuejs vscode unbound breakpoint 
Javascript :: reverse array without using another array js 
Javascript :: change property in array of objects javascript 
Javascript :: regex data 
Javascript :: async javascript 
Javascript :: how to loop trough an object java script 
Javascript :: cookie options 
Javascript :: javascript count character in string 
Javascript :: dynamically change meta tags javascript 
Javascript :: React Native Starting In Android 
Javascript :: mongodb unwind 
Javascript :: converting object to an array in javascript 
Javascript :: AWS JavaScript SDK node 
Javascript :: javascript Convert to Boolean Explicitly 
Javascript :: A simple static file server built with Node.js 
Javascript :: js remove form object by key 
Javascript :: jquery scroll to element in scrollable div 
Javascript :: javascript is url 
Javascript :: requestanimationframe 
Javascript :: check if number is float 
Javascript :: angular rellax 
Javascript :: How to check if an item is selected from an HTML drop down list with javascript js 
Javascript :: ref in mongoose example 
Javascript :: MAC addresses in JavaScript 
Javascript :: add 2 for hours in date timestamp js 
Javascript :: react dynamic import 
Javascript :: jquery console log 
ADD CONTENT
Topic
Content
Source link
Name
8+2 =