react-detect-click-outside
react-detect-click-outside copied to clipboard
Not working in different instances of the component.
Hi, first of all, thanks for this package. It works great.
I encountered a problem while trying to implement two instances of the same component with the "useDetectClickOutside" approach. It is not working in the second instance, it just triggers close when clicking and closes all.
I tried by adding unique key in each component instance, but it keeps failing.
Thanks.
Hi @davidmoreno92 , thanks for calling this out. I haven't had much time to devote to this package lately, but if you or anyone else is willing to find a fix, I'll happily review it and merge it if it works!
I will try if i have time mate. Thanks.
This happens because only a single click listener is actually added to the DOM, or something like that. I managed to get multiple instances working by conditionally setting the ref attribute to the many elements.
There is a single ref object with different trigger functions:
const citySelectorRef = useDetectClickOutside({
onTriggered:
focusedField === 'ORIGIN'
? handleOriginInputBlur
: handleDestinationInputBlur
});
And in the JSX the ref is defined accordingly:
ref={focusedField === 'ORIGIN' ? citySelectorRef : undefined}
Update: I found a problem with this approach. When changing focus between inputs with ref, the callback is not triggered, what could it be?
I cannot reproduce this problem at all. I think it works fine for multiple instances of same component.
I created a CodeSandbox demo here:
https://codesandbox.io/s/brave-pare-1j8xsm?file=/src/App.tsx
There you can see that two boxes behave correctly:
- If you click outside of both boxes, both boxes trigger count increment.
- If you click in the first box, only second box triggers count increment.
- If you click in the second box, only first box triggers count increment.