Repository navigation
feat(useOutsideClickRef): add a hook that returns a callback ref for outside clicks - #616
Conversation
🦋 Changeset detectedLatest commit: 99294cb The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Size Change: +2.7 kB (+2.13%) Total Size: 130 kB 📦 View Changed
ℹ️ View Unchanged
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## v1-base #616 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 76 77 +1
Lines 2446 2507 +61
Branches 792 814 +22
=========================================
+ Hits 2446 2507 +61 🚀 New features to boost your workflow:
|
Choi-Jung-Hyeon
left a comment
There was a problem hiding this comment.
Read through it and ran the tests locally, looks good to me. One question inline.
| [enabled, handleOutsideClick] | ||
| ); | ||
|
|
||
| return useCallback(function attachElement(element: Element | null) { |
There was a problem hiding this comment.
If the ref moves to another element while the first one stays rendered, the first one is still treated as inside. For example, ref={i === selected ? ref : undefined}: after selected changes, clicking the old item doesn't call onOutsideClick.
Returning a cleanup (return () => elementsRef.current.delete(element)) fixes it on React 19, but then keeps an element hidden by Suspense as attached fails, since React 19 also runs ref cleanups when Suspense hides content. So I guess keeping elements until they disconnect is on purpose. If so, maybe worth a line in the docs that the ref should stay on the same element?
There was a problem hiding this comment.
yeah it's on purpose. the cleanup fix would make react 18 and 19 behave differently, plus change what happens while suspense hides the content.
instead of a docs line, i added a test that pins it as a known limit in e7a3a21, so we can flip it once we only support react 19+ 🙏
Antoliny0919
left a comment
There was a problem hiding this comment.
Looks good to me 👍👍 Great work 👍👍
I left a few minor comments, could you take a look?
| # useOutsideClickEffect | ||
|
|
||
| `useOutsideClickEffect`는 지정한 컨테이너 외부에서 클릭 이벤트가 발생하면 콜백을 실행하는 리액트 훅이에요. 외부를 클릭했을 때 모달, 드롭다운, 툴팁 같은 UI 컴포넌트를 닫는 데 유용해요. | ||
| `useOutsideClickEffect`는 지정한 컨테이너 외부에서 클릭 이벤트가 발생하면 콜백을 실행하는 리액트 훅이에요. 외부를 클릭했을 때 모달, 드롭다운, 툴팁 같은 UI 컴포넌트를 닫는 데 유용해요. 여러 요소를 각각 상태로 관리하지 않고 내부로 취급하려면 모든 요소에 연결할 ref 하나를 반환하는 [`useOutsideClickRef`](/ko/hooks/useOutsideClickRef)를 사용하세요. |
There was a problem hiding this comment.
개인적으로 **“내부로 취급하려면”**이라는 부분이 조금 어렵게 느껴졌어요.
흐름상 영역을 의미한다는 건 알겠지만, 어떤 요소를 기준으로 내부와 외부를 나누고 어떤 클릭에 콜백이 실행되는지 바로 이해하기는 어려웠던거 같습니다.
e.g. “버튼과 메뉴처럼 여러 요소의 바깥을 클릭했을 때 콜백을 실행하려면 useOutsideClickRef를 사용하세요.”
위 문장처럼 구체적인 예시를 통해서 설명하는 건 어떨까요?
There was a problem hiding this comment.
좋네요 👍 다만 "여러 요소의 바깥"만 쓰면 하나라도 바깥이면 실행되는 걸로 읽힐 수 있어서, "한 영역으로 묶고"를 같이 넣었어요. bc6d2b9
| handleOutsideClick(); | ||
| } | ||
|
|
||
| document.addEventListener('click', handleClick, true); |
There was a problem hiding this comment.
index 1f74945..c2beb28 100644
--- a/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.ts
+++ b/packages/react-simplikit/src/hooks/useOutsideClickRef/useOutsideClickRef.ts
@@ -96,10 +96,10 @@ export function useOutsideClickRef({
handleOutsideClick();
}
- document.addEventListener('click', handleClick, true);
+ document.addEventListener('click', handleClick, { capture: true });
return () => {
- document.removeEventListener('click', handleClick, true);
+ document.removeEventListener('click', handleClick, { capture: true });
};
},
[enabled, handleOutsideClick]Could we use { capture: true } here to make it clearer that the listener runs during the capture phase?
There was a problem hiding this comment.
good call, reads much clearer 👍 changed the pointerdown one too so the file uses one form. 0fe6617
| toolbar.remove(); | ||
| }); | ||
|
|
||
| it('drops disconnected elements when another element attaches', () => { |
There was a problem hiding this comment.
From the test name, I understood that this test checks whether elements removed from the DOM are cleaned up when a new element is registered. However, since cleanup also runs in the click handler, checking only the result after a click doesn’t seem to distinguish whether cleanup happened during registration.
If my understanding is correct, should we verify that those elements are cleaned up at registration time?
There was a problem hiding this comment.
you're right, the click handler cleans up too, so it passed even without the cleanup on attach 😅 now it puts a back in the document and clicks it, so only the cleanup on attach can make it count as outside. checked that it fails once that line is removed. 96e6d64
mnxmnz
left a comment
There was a problem hiding this comment.
Thank you for the work and the reviews! The open comments look minor to me, so I'm approving.
LGTM 👍
…with an example in ko
Overview
Closes #611
useOutsideClickEffecttakes the elements, so a trigger and its menu each need their own state and setter. This addsuseOutsideClickRef, which returns one callback ref to attach to every element that counts as inside.{ onOutsideClick, enabled }, like the other v1 hooks.enableddefaults totrue; pass the open state so a trigger holding the ref doesn't call back while the menu is closed.clickand remembers where thepointerdownstarted. A press that starts inside and ends outside, such as dragging a text selection out, is not an outside click, and starting a touch scroll doesn't close the menu.stopPropagationor a handler that removes its own element doesn't change the result. The callback runs before the clicked element's ownonClick.composedPath(), so it also works inside open shadow roots. The ref keeps its elements in a set, ignoresref(null)and drops elements that left the document, so React 16.8 to 19 take the same path.useOutsideClickEffectis unchanged. Its docs now point to the new hook.Checked in Safari on the iOS 18.5 simulator: taps on plain elements with no click listener, both outside the React root and on
body, reach thedocumentlistener. The older iOS issue where such taps never reachdocument(vueuse/vueuse#1520, React's workaround) doesn't show up.Limits:
composedPath().Checklist
yarn run fixto format and lint the code and docs?yarn run test:coverageto make sure there is no uncovered line?