react-detect-click-outside icon indicating copy to clipboard operation
react-detect-click-outside copied to clipboard

Not working in different instances of the component.

Open davidmoreno92 opened this issue 3 years ago • 4 comments

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.

davidmoreno92 avatar May 11 '22 14:05 davidmoreno92

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!

zhaluza avatar Jun 04 '22 17:06 zhaluza

I will try if i have time mate. Thanks.

davidmoreno92 avatar Jun 04 '22 19:06 davidmoreno92

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?

devguilhermy avatar Jul 28 '22 21:07 devguilhermy

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.

leodevbro avatar Apr 14 '23 23:04 leodevbro