Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

handleClickoutside custom hook react

import { useState, useEffect, useRef } from 'react';

export default function useComponentVisible(initialIsVisible) {
    const [isComponentVisible, setIsComponentVisible] = useState(initialIsVisible);
    const ref = useRef<HTMLDivElement>(null);

    const handleHideDropdown = (event: KeyboardEvent) => {
        if (event.key === 'Escape') {
            setIsComponentVisible(false);
        }
    };

    const handleClickOutside = (event: Event) => {
        if (ref.current && !ref.current.contains(event.target as Node)) {
            setIsComponentVisible(false);
        }
    };

    useEffect(() => {
        document.addEventListener('keydown', handleHideDropdown, true);
        document.addEventListener('click', handleClickOutside, true);
        return () => {
            document.removeEventListener('keydown', handleHideDropdown, true);
            document.removeEventListener('click', handleClickOutside, true);
        };
    });

    return { ref, isComponentVisible, setIsComponentVisible };
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: how to check electron verion 
Javascript :: get form data in js 
Javascript :: javascript datatypes 
Javascript :: kick members node js 
Javascript :: module pattern function syntax 
Javascript :: detect keyboard open or close in react js 
Javascript :: Sort an array by both ascending and descending order in js 
Javascript :: how to format datetime in javascript 
Javascript :: timestamp to date 
Javascript :: ruby on rails test if all parameters in json request are here 
Javascript :: js convert object to array 
Javascript :: js loop through form inputs 
Javascript :: Javascript Map properties and methods 
Javascript :: how to get the text of a clicked elemet by javascript 
Javascript :: js object getter 
Javascript :: sort array without changing the original js 
Javascript :: javascript remove required attribute 
Javascript :: Prevent Double tap in React native 
Javascript :: mongodb node js 
Javascript :: How to loop through an object in JavaScript with the Object.values() method 
Javascript :: numero random en js 
Javascript :: The slice JavaScript string method 
Javascript :: http module nodejs 
Javascript :: react onchange multiple functions 
Javascript :: Expected the depth of nested jsx elements to be <= 2, but found 3 
Javascript :: how to use json stringify in javascript 
Javascript :: render image in vue 
Javascript :: responseText js 
Javascript :: how can hide link from inspect element 
Javascript :: javascript regex One or more occurrences of the pattern 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =