Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not working in different instances of the component. #16

Open
davidmoreno92 opened this issue May 11, 2022 · 4 comments
Open

Not working in different instances of the component. #16

davidmoreno92 opened this issue May 11, 2022 · 4 comments

Comments

@davidmoreno92
Copy link

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.

@zhaluza
Copy link
Owner

zhaluza commented Jun 4, 2022

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!

@davidmoreno92
Copy link
Author

I will try if i have time mate. Thanks.

@devguilhermy
Copy link

devguilhermy commented Jul 28, 2022

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?

@leodevbro
Copy link

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.

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

No branches or pull requests

4 participants