Тёмный

Click Outside to Close - React Hook 

Ryan Toronto
Подписаться 4,4 тыс.
Просмотров 51 тыс.
50% 1

In this video I'll show you how to make a hook that runs whenever the user clicks outside of a DOM node.
Source: / little-neat-trick-to-c...
Code: github.com/ryanto/click-outsi...

Опубликовано:

 

26 апр 2020

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 147   
@codymccarty9327
@codymccarty9327 2 года назад
Cannot read property 'contains' can be fixed by changing current.contains to current?.contains
@luishenriqueandradepellizz680
I had the same problem, but then I realized we need to check where we want to reference using the useRef. When you create a dropdown like that, you need to reference the whole div that contains the Button and the Dropdown menu. My mistake was, I put the ref prop only in the dropdown menu, and above was my button to toggle the dropdown, when I move my ref to the whole div that contains both button and dropdown, it solved the problem, because on the useEffect we want to setClose if the ref contains the div. It will return undefined because if you hide the dropdown menu and reference it using useRef, when the react mounts, the reference will be undefined, because it is hidden. Putting the ref ={} on the div that holds both button and dropdown menu solved the problem.
@matthewokadinya6514
@matthewokadinya6514 Год назад
You're amazing... Thanks
@alirasheedmd
@alirasheedmd 3 года назад
What a great simple-to-understand solution. I was searching for this all over the web and could not find this kind of solution. Thanks a lot, man.
@dschenck
@dschenck 3 года назад
Thanks, very clear! Thanks for taking that one extra step at the end about designing a reusable hook :)
@salymakhmedov2196
@salymakhmedov2196 3 года назад
Thank you for this. I used this code in my project and referenced this video in the code. Please make more practical videos like this!
@sjadev
@sjadev 3 года назад
This was exactly what I was looking for! Thanks, Ryan!
@ygg.gasoline
@ygg.gasoline 2 года назад
your way of doing it was much easier, faster and clearer then others i saw online. thank you!!
@EmilyNilsen
@EmilyNilsen 2 года назад
What a clear explanation, thank you so much, Ryan! My problem is now solved and you have a faithful new subscriber.
@DevRSC
@DevRSC Год назад
Clear and straightforward explanation, just what I'm looking for thanks.
@ewertoncassianoxavier3490
@ewertoncassianoxavier3490 2 года назад
Thank you very much for the excellent explanation, Ryan! Your code worked like a charm!
@vancouverjunkremoval
@vancouverjunkremoval 3 года назад
Thanks for this vid ryan! amazingly well explained! I gave helped solve that feature I didn't know how to implement with hooks
@lazer1182
@lazer1182 2 года назад
This explanation is 100% clear. Teaching style is great
@ezequielvallejo9352
@ezequielvallejo9352 2 года назад
It is in fact very nice Ryan, your explanation also, clear and concise. Thanks a lot! Greetings from Argentina.
@adarshshete7987
@adarshshete7987 3 года назад
Not only I got perfect solution for my problem But also I learned a new cool technique (creating hook) to handle this problem with more efficiency ! Thank you very much !!!!
@elasriabdelhamid5659
@elasriabdelhamid5659 3 года назад
You saved my life. I've been searching for this for months, thanks a lot.
@ShubhamBohra108
@ShubhamBohra108 9 месяцев назад
Thanks Mate . Great explanation and it was short and to the point
@fazlechistyhimel3958
@fazlechistyhimel3958 3 года назад
Thank you so so much. I was looking for this for a long time. May God bless you.
@adamdurrant
@adamdurrant Год назад
Excellent explanation, super helpful - I built some cool modals with this. Thank you Ryan :)
@thiagonunesbatista6887
@thiagonunesbatista6887 3 года назад
Thanks for you from Brazil!!! You helped me a lot
@bismarckkaine2700
@bismarckkaine2700 3 года назад
Well done Ryan, this was very helpful for me.
@praveethbabu
@praveethbabu 2 года назад
You beauty... What a clear explanation. Hats off sir. I immediately subscribed to your channel. You are a great teacher. Thanks a lot 👍👍
@MrThalif
@MrThalif 4 года назад
thank you for the video, the explanations were very clear and it helped me a lot !
@algorithm6232
@algorithm6232 Год назад
amazing work... straight to point, thank you so much!
@brunomcsilva5404
@brunomcsilva5404 2 года назад
Great job Ryan! Superbe explanation!
@ebiwarimeshach4707
@ebiwarimeshach4707 Год назад
Simple and precise.....you just saved the day champ
@geezer74
@geezer74 3 года назад
God Damn!! This was brilliant, no one else online has a solution like this!⭐⭐⭐⭐⭐
@Flamability9
@Flamability9 3 года назад
Thank you for the video! Saved me so much time.
@techyguy7776
@techyguy7776 2 года назад
Great explanation ryan keep up the good work!
@LordzChilight
@LordzChilight 2 года назад
Thank you so much Ryan, its really helpful
@joycemeow5857
@joycemeow5857 2 года назад
You teach so well! Thanks!
@faisalahmad100
@faisalahmad100 2 года назад
Many many thanks Sir...🙂🙂 I've solved a problem watching your video🙂
@marimuthur9456
@marimuthur9456 2 года назад
Excellent trick thank you so much 👌🏼👌🏼👌🏼
@chineduknight6426
@chineduknight6426 3 года назад
This is a simple but powerful solution really handy
@joeyvico
@joeyvico 2 года назад
Exactly what I needed to learn, thanks
@Elias-xp3bs
@Elias-xp3bs 2 года назад
Great video! Very well explained
@ahmedAli-yc2js
@ahmedAli-yc2js 3 года назад
So perfect. Thank you so much 🙏🙏
@andersbraathen1256
@andersbraathen1256 2 года назад
Thank you! Great video
@moayedmahmod5283
@moayedmahmod5283 7 месяцев назад
thank you so much this video was so helpful
@devanshitank7119
@devanshitank7119 3 года назад
Great explanation!
@abdulazizsalokhiddinov
@abdulazizsalokhiddinov 3 года назад
it is working, just amazing, thank you bro
@safargaadika4174
@safargaadika4174 3 года назад
very nice video it saved my precious time. Thankyou.
@psychopath_syd
@psychopath_syd 3 года назад
Even though I was searching for Vue solution but yours is expressive. Maybe I'll write something like this using Vue
@GauravKumar-dw2ml
@GauravKumar-dw2ml Год назад
Thankyou so much , it really helped.
@PejeGamerGZ
@PejeGamerGZ 2 года назад
Thanks so much for the video man, it really help me a lot, I'm so gratefull :)
@sergiopile6102
@sergiopile6102 3 года назад
the way of doing the coding makes it better to understand the context and help to lose less time each time we go through it for a modification or anything. As if when riding a bike, if every time we need to assembly it and then ride it, it is better if it's ready and prepared just like normally would be.
@wellemangrey3645
@wellemangrey3645 2 года назад
Да где ты раньше был? СПАСИБО!
@thabosiphiwemngoma1859
@thabosiphiwemngoma1859 6 месяцев назад
I needed this🎉
@najmulislam344
@najmulislam344 2 года назад
Thank you very much. this video help me very mouch
@Arhirius
@Arhirius 3 года назад
I had an error 'Cannot read property 'contains' of unidentified and spend hours looking for the solution. Not sure what is different in my environment from Ryan and others, but the fix is very simple. where you have '!domNode.current.contains' you need to add 'domNode.current &&' so the full line will look like this: if ('domNode.current && !!domNode.current.contains(target.event)) {
@RyanToronto
@RyanToronto 3 года назад
Thanks for fixing that Alexey! I'm sure this will help others that run into the same problem.
@arsamrahmaan8812
@arsamrahmaan8812 3 года назад
thank you so much
@martinlinden937
@martinlinden937 3 года назад
I had the same error. It did the trick, thanks!
@jjmajano4779
@jjmajano4779 3 года назад
I had same problem but I follow what you say but still having issues, do you have a example code working?
@ricardocambundo2527
@ricardocambundo2527 3 года назад
I'm going through that right now kkk. Hope you're comment works
@jamesyeo5469
@jamesyeo5469 2 года назад
You save my day Thanks :)
@udochukwuogbulafor704
@udochukwuogbulafor704 3 года назад
Thank you for the video.
@Polish2075
@Polish2075 3 года назад
Thanks, I like your style... :)
@ImpendingSole13
@ImpendingSole13 3 года назад
Thank you so much. It helped
@HumayraSheikh1
@HumayraSheikh1 Год назад
Thank you bro 🎉
@davidcedeno878
@davidcedeno878 2 года назад
thank you so much you helped me a lot
@chandramanikandan3594
@chandramanikandan3594 3 года назад
Thank you it helped me lot
@timotijevicvladimir4870
@timotijevicvladimir4870 2 года назад
Nice explanation :-)
@sergelengerelmaa2450
@sergelengerelmaa2450 2 года назад
Nice man, thank you
@ahnafabir11
@ahnafabir11 2 года назад
you are a life saver
@melvincolmenares8665
@melvincolmenares8665 2 года назад
thank you bro i don't speak english very well but thank you for to share your knowledge
@devkima6620
@devkima6620 2 года назад
FYI, i see the comments they have problems when click button to close, the state set to true back because you wrong to put ref. put ref into wrapper click button.
@siddhant3852
@siddhant3852 2 года назад
well then we have the same problem we started with , the menu will close when we click any menu button
@LuKaSSthEBosS
@LuKaSSthEBosS 2 года назад
Thank you!
@cia-siab
@cia-siab Год назад
I noticed that after closing the menu, the mousedown event is still being called. Put a console log in the maybeHandler and you'll see the log after the menu closed.
@nwekarmahdi9211
@nwekarmahdi9211 3 года назад
well explained thanks.
@olegmaz3969
@olegmaz3969 2 года назад
Thanks a lot!
@vadykk
@vadykk 3 года назад
awesome !!! thank you so much.
@AzizKhan-or8yp
@AzizKhan-or8yp 2 года назад
thank you soo much, worked
@thankgodokpara2156
@thankgodokpara2156 3 года назад
thank you for this
@Ayush_kumar123
@Ayush_kumar123 2 года назад
This is gold
@moeinmnia
@moeinmnia 7 месяцев назад
thank you very much❤❤
@theexplored
@theexplored 2 года назад
thank you ❤❤
@sarvagya-sharma
@sarvagya-sharma 3 года назад
Amazing!
@mohamedyoussef8835
@mohamedyoussef8835 2 года назад
Awesome explanation +++++++++++++++++++++++++++++ Thank You
@estebanblancoespinoza4020
@estebanblancoespinoza4020 2 года назад
Amazing, I like this approach. Thanks!
@iamHamidur
@iamHamidur 3 года назад
Hey Ryan, You're awesome teacher. I love your teaching style. Can you tell me please what software you are using to draw rectangle area by mouse cursor which indicate the height and width? :)
@RyanToronto
@RyanToronto 3 года назад
Hi Hamidur! It's the Mac OSX screen shot tool (cmd+shift+4).
@iamHamidur
@iamHamidur 3 года назад
@@RyanToronto Thanks Ryan
@esmaeilmirzaee
@esmaeilmirzaee 3 года назад
Stupendous
@Zbaz10an
@Zbaz10an Год назад
Legend.👌
@canklc5772
@canklc5772 Год назад
Thanks for the great tutorial. I have a question. Why do we need to remove the eventlistener?
@pinjandarm
@pinjandarm 3 года назад
Thanks!
@hackhunter854
@hackhunter854 Год назад
Great it worked
@bimalskumar1464
@bimalskumar1464 3 года назад
Thank you :)
@azeemsultan7069
@azeemsultan7069 3 года назад
Thanks buddy
@wenderaugustovega214
@wenderaugustovega214 Год назад
Vim de outro pais dizer que amei o vídeo.
@richchar6478
@richchar6478 Год назад
Great explanation, ty. Question tho: what if I'm trying to do this from a component, and the state that I want to modify isn't in the component? The state is in a level above in my index.js file. I've passed the prop 'toggleState' which calls my 'toggleState()' function held in my index.js, but she ain't taking. Thanks for your help
@saadbelghiti8150
@saadbelghiti8150 Год назад
ty bro
@aljimsonmegrino9580
@aljimsonmegrino9580 3 года назад
thank u very much
@foadbotan662
@foadbotan662 Год назад
I might be wrong, but I don't think that clean-up function never gets called. My understanding is that the useEffect return func only gets called when the component it is in unmounts.
@raba650
@raba650 3 года назад
Can this work with react bootstrap nav drop down toggle button? I tried it but it’s taking 2 clicks to activate the drop down for some reason.
@yuananda
@yuananda 3 года назад
awesome, but how it supposed to work if the button component is outside the ref component?
@a_l_o_k_1991
@a_l_o_k_1991 3 года назад
Thats great one !!..... Can you please let me know why do we need to clean up the effect like removing event listner ??
@RyanToronto
@RyanToronto 3 года назад
Hi Alok! The reason we have to clean up the effect and remove the event listener is because otherwise the listener would stay attached to the document forever. Ever time we rendered a component the document would end up getting another new listener. Eventually there would be so many listeners that it would cause a memory leak. Using the cleanup function allows us to tear down the listener and prevent any sort of memory leak from ever happening.
@a_l_o_k_1991
@a_l_o_k_1991 3 года назад
@@RyanToronto Thank you so much for your response. Really helpful video.
@arako4988
@arako4988 3 года назад
thanks
@_ademmeral
@_ademmeral 4 месяца назад
thanx
@adeshgangwar3555
@adeshgangwar3555 3 года назад
Can we make this as helper function so that we can use the same functionality in other components as well. Question: in helper function case should I pass the ref as the second argument to that function?
@RyanToronto
@RyanToronto 3 года назад
No need to make a helper function. You can export the hook to share it between multiple components.
@anoopv3750
@anoopv3750 3 года назад
NIce
@nishantkumar6960
@nishantkumar6960 3 года назад
Appreciate your help? I'm eager to know, how did you come across this solution? Please... I'm asking because I want to know why I'm not able to figure out this myself on my own. What should I be really looking for and what am I really lacking that is keeping me behind.
@RyanToronto
@RyanToronto 3 года назад
Hi Nishant! React hooks are really hard to write and they don't come naturally, especially when you first start using functional components. The best way to find these solutions is to write A LOT of React. For practice try to write a few hooks on your own and then use Google and see what other people did to solve the problem.
@nishantkumar6960
@nishantkumar6960 3 года назад
@@RyanToronto Thanks Ryan for taking time for me. I feel so grateful. Thank you so much.
@JimmyCheng
@JimmyCheng Год назад
I implemented something similar, where I have a header menu with a button to open a pop-up. But somehow, the pop-up won't show because as soon as I click the button, it closes the pop-up in the mean time because I think I am technically clicking outside the pop-up. Hmmm. Someone help>?
@raba650
@raba650 9 месяцев назад
What if the toggle button is outside the node where you put the ref at? I have something like this & the button’s detected as a click outside event that when I click on, it closes the component & quickly open it again. I want to have the click outside functionality along with the toggle when the button’s outside of the ref area.
@sanjibdey01
@sanjibdey01 2 года назад
In my application, I'm navigating between routes. The event handler works fine when I'm on the concerned page, but since component mounts/unmounts with route changes, "ref.current" was going back to "null" when routing back to the page, thus throwing error: "Cannot read property 'contains' of null" . 😅Easy fix: clean-up handler function with "removeEventListener".
@RyanToronto
@RyanToronto 2 года назад
Awesome fix Sanjib! I'll pin your comment because I'm sure it will help others.
@sanjibdey01
@sanjibdey01 2 года назад
@@RyanToronto Happy to help. Thanks for the easy tutorial.
@adithyakiransekar
@adithyakiransekar Год назад
What if you had multiple menus on the same page? The document click listeners will be attached multiple times
@romanmed9035
@romanmed9035 Год назад
can it work for 2 elements? example dropdown when opened first then i click to second.
@joelomoglio6450
@joelomoglio6450 Год назад
I have it working with one menu component on the page that uses the hook, but when I have multiple menu components on the page, only one of them works properly, the other ones close outside and when you click the menu. If that can be resolved, how can Imake this a global hook, so I don't have to have it it my menu and select components?
@Richard-wg4lu
@Richard-wg4lu Год назад
i have done this but if i giving the same ref in the another div in the same component. The another div working perfectly but the first div have an issue that when i click the button it opens but if i click the button again it toggles to close and opens automatically. Do i have to use two different refs or something?
Далее
Why Signals Are Better Than React Hooks
16:30
Просмотров 463 тыс.
useRef hook in reactjs | Easiest way
19:44
Просмотров 74 тыс.
вот тебе и бэйбик👴🏻
01:00
Просмотров 323 тыс.
В GEOMETRY DASH СДЕЛАЛИ GTA
00:27
Просмотров 380 тыс.
Stray Kids "Chk Chk Boom" M/V
03:26
Просмотров 28 млн
Click Outside to Close - React Hook
6:37
Просмотров 60 тыс.
Detect Clicks Anywhere on a Page in React
12:10
Просмотров 2,6 тыс.
React VS Svelte...10 Examples
8:35
Просмотров 534 тыс.
You might not need useEffect() ...
21:45
Просмотров 154 тыс.
Turning bad React code into senior React code
13:10
Просмотров 87 тыс.