Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

useClickAway should support one or more elements

Abierto
#2,490 2 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
Medio día
Aptitud para principiantes
48/100
Tipo de issue
Nueva funcionalidad
Claridad
Bien especificado
Estado de actividad
Estancado
Stack tecnológico
react, typescript
Área
frontend

Línea de trabajo

Read src/useClickAway.ts and compare its current single-ref API with the multiple-ref implementation described in the issue. Verify that a click invokes the callback only when it is outside every observed element, while the existing single-element behavior and toggle case remain intact.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

I have a case where a popover is supposed to be closed when I click anything outside the popover. The button which triggers the popover also works as a toggle, i. e. clicking it again closes the popover. This behavior is quite common and intuitive and should be preserved. Now, using useClickAway I can close the popover but when I try to do the same via toggling said button, the events interfere with each other and result in the popover being displayed again (the click outside closing it and the click on the button showing it again).

The apparent fix would be to allow useClickAway to receive one element or a list of elements and in the latter case only invoke the callback function if the click happened outside all observed elements.

I've adapted the useClickAway implementation to do this as follows and it works for my specific case:

import type { MutableRefObject } from "react";
import { useEffect, useRef } from "react";
import { off, on } from "react-use/lib/misc/util";

const defaultEvents = ["mousedown", "touchstart"];

// This is based on react-use's clickAway hook but made to work with multiple refs in addition to a single ref,
// meaning the click needs to happen outside all registered refs.
// See https://github.com/streamich/react-use/blob/master/src/useClickAway.ts for the original hook
export function useClickAway<
  T extends Element | null = Element,
  E extends Event = Event
>(
  refs: Array<MutableRefObject<T>>,
  onClickAway: (event: E) => void,
  events: string[] = defaultEvents
): void {
  const savedCallback = useRef(onClickAway);
  const savedRefs = useRef(refs);
  useEffect(() => {
    savedCallback.current = onClickAway;
    savedRefs.current = refs;
  }, [onClickAway, refs]);

  useEffect(() => {
    const handler = (event: E) => {
      const clickedOutside = savedRefs.current.every(ref => {
        const { current: el } = ref;
        return el && !el.contains(event.target as Node);
      });
      if (clickedOutside) {
        savedCallback.current(event);
      }
    };
    for (const eventName of events) {
      on(document, eventName, handler);
    }
    return () => {
      for (const eventName of events) {
        off(document, eventName, handler);
      }
    };
  }, [events]);
}

I'd appreciate it if something like that became available upstream so I could get rid of my custom implementation. I could also make a PR if that's increases the chance of it being made available upstream.

Lenguaje dominante
TypeScript
Estrellas
44k
Forks
3.3k
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de streamich/react-use

Todos los issues de streamich/react-use

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.