Skip to content

Conversation

@SayaOvO
Copy link

@SayaOvO SayaOvO commented Dec 26, 2024

please review

import { useClickOutside } from 'foxact/use-click-outside';

function Component() {
const ref = useClickOutside<HTMLDivHTML>(() => {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const ref = useClickOutside<HTMLDivHTML>(() => {
const ref = useClickOutside<HTMLDivElement>(() => {

Comment on lines 8 to 18
useEffect(() => {
const handleClick = ({ target }: MouseEvent) => {
if (target && ref.current && !ref.current.contains(target as Node)) {
cb();
}
};
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
}, [cb]);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use callback ref instead of useEffect.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you Sukka sensei !
Here is my implementation, please review :)

import 'client-only';
import { useCallback } from 'react';
import type { RefCallback } from 'react';

export function useClickOutside<T extends HTMLElement>(cb: () => void): RefCallback<T> {
  return useCallback((node) => {
    const handleClick = ({ target }: MouseEvent) => {
      if (target && node && !node.contains(target as Node)) {
        cb();
      }
    };
    document.addEventListener('click', handleClick);
    return () => {
      document.removeEventListener('click', handleClick);
    };
  }, [cb]);
}

but as far as I know, ref callback can return a cleanup function only from React 19, before React 19, React would call this callback with null value when unmount. Shouldn't we consider this situation or am I incorrectly implementing this hook? :)


<ExportMetaInfo />

`useClickOutside` calls the callback you provide when a click event occurs outside the element associated with the returned ref callback
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably document that this only works on React 19 since we use ref callback cleanup. Or is it possible to make it backward compatible with the previous React version?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants