click outside React component
const componentRef = useRef();

useEffect(() => {
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
    function handleClick(e: any) {
        if(componentRef && componentRef.current){
            const ref: any = componentRef.current
            if(!ref.contains(e.target)){
                // put your action here
            }
        }
    }
}, []);
react click outside
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>;
}
react click outside class implementation
import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * Component that alerts if you click outside of it
 */
export default class OutsideAlerter extends Component {
    constructor(props) {
        super(props);

        this.wrapperRef = React.createRef();
        this.setWrapperRef = this.setWrapperRef.bind(this);
        this.handleClickOutside = this.handleClickOutside.bind(this);
    }

    componentDidMount() {
        document.addEventListener('mousedown', this.handleClickOutside);
    }

    componentWillUnmount() {
        document.removeEventListener('mousedown', this.handleClickOutside);
    }

    /**
     * Alert if clicked on outside of element
     */
    handleClickOutside(event) {
        if (this.wrapperRef && !this.wrapperRef.current.contains(event.target)) {
            alert('You clicked outside of me!');
        }
    }

    render() {
        return <div ref={this.wrapperRef}>{this.props.children}</div>;
    }
}

OutsideAlerter.propTypes = {
    children: PropTypes.element.isRequired,
};
outside click 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)

TypeScript相关代码片段

reset form in angular typescript

nextjs get url params api app route

select between brackets vscode macbook

vercel config for express

jest it sleep

tailwindcss-debug-screens

MY_MOMENT_FORMATS LT

nextjs multiple image hostnames

DatetimeFormatOptions typescript

typescript generic

typescript Dictionary

npm circuit breaker

angular httpinterceptor + for file uploads

comments using regex

nestjs client streaming grpc client

nodejs curicuit breaker

data table tanstack custom pagination number

typescript interface react

typescript get keys of type

jest testing ts

jest sleep between tests too many requests

disable prop types eslint

exports is not defined

ts any key in object

cypress configure browser size

i18next change language

i18n change language

nextjs 14 route api creation

i18next check current language

arc shortcuts windows

sequelize relation where

typescript omit for enums

setup TypeScript in tsconfig.json

typescript is checking types from user directory

vite.config.ts resolve

zod one of string

sequelize where relationship

collapsable sidebar shadcn

ts disable its value is never used

rtk query programmatically

papa parse convert to object

Overflow:hidden dots at the end

awaited typescript

typescript print to console

git how to view all commits before push

how to use external fonts in react

change shadcn select placeholder color

ts get type of object values

How to add todo

zod error message

tailwindcss screen debugger in nextjs

does fcm automatically starts on reboot?

run vite app

max amount validator

redis client type typescript

omit more than one typescript

vscode md snippets for mdx also

check if user exists firebase

add custom class in tailwindcss

initialize array of specific size

typescript create type from array of strings

shadcn dialog programmatically

nodejs file stream

observablehq copy data

object is possibly 'null'.ts(2531)

start a typescript backend nodejs

nestjs http module

typing when fetching data in ts

ts nspell usage

Custom Painting Template

export import ts interface

how to add fonts to flutter

sequelize literal attributes

passing react component as variables

sequelize returning update

how to initialize/setup typescript

types for typescript as const

TypeScript Aliases

uniqe uuid

comment in typescript react