Click Outside to Close - React Hook

Поделиться
HTML-код
  • Опубликовано: 5 янв 2025

Комментарии • 147

  • @codymccarty9327
    @codymccarty9327 3 года назад +23

    Cannot read property 'contains' can be fixed by changing current.contains to current?.contains

    • @luishenriqueandradepellizz680
      @luishenriqueandradepellizz680 2 года назад +4

      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

    • @zhuochen8793
      @zhuochen8793 5 месяцев назад

      @@luishenriqueandradepellizz680 thank you for your comment!! big help!!

  • @alirasheedmd
    @alirasheedmd 3 года назад +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.

  • @sjadev
    @sjadev 3 года назад +5

    This was exactly what I was looking for! Thanks, Ryan!

  • @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 !!!!

  • @dschenck
    @dschenck 4 года назад +3

    Thanks, very clear! Thanks for taking that one extra step at the end about designing a reusable hook :)

  • @DevRSC
    @DevRSC 2 года назад +1

    Clear and straightforward explanation, just what I'm looking for thanks.

  • @gasgodgasoline
    @gasgodgasoline 2 года назад

    your way of doing it was much easier, faster and clearer then others i saw online. thank you!!

  • @ShubhamBohra108
    @ShubhamBohra108 Год назад

    Thanks Mate . Great explanation and it was short and to the point

  • @EmilyNilsen
    @EmilyNilsen 3 года назад +2

    What a clear explanation, thank you so much, Ryan! My problem is now solved and you have a faithful new subscriber.

  • @salymakhmedov2196
    @salymakhmedov2196 3 года назад +2

    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!

  • @ezequielvallejo9352
    @ezequielvallejo9352 2 года назад

    It is in fact very nice Ryan, your explanation also, clear and concise. Thanks a lot! Greetings from Argentina.

  • @faisalahmad100
    @faisalahmad100 3 года назад

    Many many thanks Sir...🙂🙂
    I've solved a problem watching your video🙂

  • @ebiwarimeshach4707
    @ebiwarimeshach4707 2 года назад

    Simple and precise.....you just saved the day champ

  • @praveethbabu
    @praveethbabu 3 года назад

    You beauty... What a clear explanation. Hats off sir. I immediately subscribed to your channel. You are a great teacher. Thanks a lot 👍👍

  • @elasriabdelhamid5659
    @elasriabdelhamid5659 3 года назад

    You saved my life. I've been searching for this for months, thanks a lot.

  • @chineduknight6426
    @chineduknight6426 4 года назад

    This is a simple but powerful solution really handy

  • @fazlechistyhimel3958
    @fazlechistyhimel3958 3 года назад +1

    Thank you so so much. I was looking for this for a long time. May God bless you.

  • @vancouverjunkremoval
    @vancouverjunkremoval 3 года назад +1

    Thanks for this vid ryan! amazingly well explained! I gave helped solve that feature I didn't know how to implement with hooks

  • @lyuftwaffelnica
    @lyuftwaffelnica 2 года назад

    That was exactly what I was looking for! Thank you, Ryan!

  • @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.

  • @thiagonunesbatista6887
    @thiagonunesbatista6887 4 года назад +1

    Thanks for you from Brazil!!! You helped me a lot

  • @ewertoncassianoxavier3490
    @ewertoncassianoxavier3490 3 года назад

    Thank you very much for the excellent explanation, Ryan! Your code worked like a charm!

  • @adamdurrant
    @adamdurrant Год назад

    Excellent explanation, super helpful - I built some cool modals with this. Thank you Ryan :)

  • @devkima6620
    @devkima6620 2 года назад +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!

  • @geezer74
    @geezer74 3 года назад

    God Damn!! This was brilliant, no one else online has a solution like this!⭐⭐⭐⭐⭐

  • @psychopath_syd
    @psychopath_syd 3 года назад +1

    Even though I was searching for Vue solution but yours is expressive. Maybe I'll write something like this using Vue

  • @techyguy7776
    @techyguy7776 2 года назад

    Great explanation ryan keep up the good work!

  • @bismarckkaine2700
    @bismarckkaine2700 3 года назад

    Well done Ryan, this was very helpful for me.

  • @brunomcsilva5404
    @brunomcsilva5404 3 года назад

    Great job Ryan! Superbe explanation!

  • @marimuthur9456
    @marimuthur9456 2 года назад

    Excellent trick thank you so much 👌🏼👌🏼👌🏼

  • @cia-siab
    @cia-siab 2 года назад

    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.

  • @EveryCountry11
    @EveryCountry11 2 года назад

    amazing work... straight to point, thank you so much!

  • @joeyvico
    @joeyvico 2 года назад

    Exactly what I needed to learn, thanks

  • @AnimeMoments6000
    @AnimeMoments6000 3 года назад

    Thank you for the video! Saved me so much time.

  • @LordzChilight
    @LordzChilight 3 года назад

    Thank you so much Ryan, its really helpful

  • @MrThalif
    @MrThalif 4 года назад

    thank you for the video, the explanations were very clear and it helped me a lot !

  • @thabosiphiwemngoma1859
    @thabosiphiwemngoma1859 Год назад

    I needed this🎉

  • @melvincolmenares8665
    @melvincolmenares8665 3 года назад

    thank you bro i don't speak english very well but thank you for to share your knowledge

  • @joycemeow5857
    @joycemeow5857 2 года назад

    You teach so well! Thanks!

  • @Arhirius
    @Arhirius 3 года назад +32

    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 года назад +3

      Thanks for fixing that Alexey! I'm sure this will help others that run into the same problem.

    • @arsamrahmaan8812
      @arsamrahmaan8812 3 года назад +2

      thank you so much

    • @martinlinden937
      @martinlinden937 3 года назад +1

      I had the same error. It did the trick, thanks!

    • @jjmajano4779
      @jjmajano4779 3 года назад +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

  • @andersbraathen1256
    @andersbraathen1256 2 года назад

    Thank you! Great video

  • @PejeGamerGZ
    @PejeGamerGZ 2 года назад

    Thanks so much for the video man, it really help me a lot, I'm so gratefull :)

  • @moayedmahmod5283
    @moayedmahmod5283 Год назад

    thank you so much this video was so helpful

  • @Elias-xp3bs
    @Elias-xp3bs 2 года назад

    Great video! Very well explained

  • @abdulazizsalokhiddinov
    @abdulazizsalokhiddinov 3 года назад

    it is working, just amazing, thank you bro

  • @wellemangrey3645
    @wellemangrey3645 2 года назад

    Да где ты раньше был? СПАСИБО!

  • @raba650
    @raba650 Год назад

    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.

  • @JimmyCheng
    @JimmyCheng 2 года назад

    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>?

  • @GauravKumar-dw2ml
    @GauravKumar-dw2ml 2 года назад

    Thankyou so much , it really helped.

  • @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?

  • @ahnafabir11
    @ahnafabir11 2 года назад

    you are a life saver

  • @devanshitank7119
    @devanshitank7119 3 года назад

    Great explanation!

  • @jamesyeo5469
    @jamesyeo5469 2 года назад

    You save my day Thanks :)

  • @adi_sekar
    @adi_sekar 2 года назад

    What if you had multiple menus on the same page? The document click listeners will be attached multiple times

  • @yuananda
    @yuananda 3 года назад

    awesome, but how it supposed to work if the button component is outside the ref component?

  • @safargaadika4174
    @safargaadika4174 3 года назад

    very nice video it saved my precious time. Thankyou.

  • @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?

  • @ahmedAli-yc2js
    @ahmedAli-yc2js 4 года назад

    So perfect. Thank you so much 🙏🙏

  • @HumayraSheikh1
    @HumayraSheikh1 Год назад

    Thank you bro 🎉

  • @richchar6478
    @richchar6478 2 года назад

    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

  • @foadbotan662
    @foadbotan662 2 года назад

    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.

  • @romanmed9035
    @romanmed9035 Год назад

    can it work for 2 elements? example dropdown when opened first then i click to second.

  • @timotijevicvladimir4870
    @timotijevicvladimir4870 3 года назад

    Nice explanation :-)

  • @najmulislam344
    @najmulislam344 3 года назад

    Thank you very much. this video help me very mouch

  • @Ayush_kumar123
    @Ayush_kumar123 2 года назад

    This is gold

  • @udochukwuogbulafor704
    @udochukwuogbulafor704 4 года назад

    Thank you for the video.

  • @estebanblancoespinoza4020
    @estebanblancoespinoza4020 3 года назад

    Amazing, I like this approach. Thanks!

  • @sergelengerelmaa2450
    @sergelengerelmaa2450 2 года назад

    Nice man, thank you

  • @nishantkumar6960
    @nishantkumar6960 4 года назад +1

    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  4 года назад +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 4 года назад +1

      @@RyanToronto Thanks Ryan for taking time for me. I feel so grateful. Thank you so much.

  • @canklc5772
    @canklc5772 2 года назад

    Thanks for the great tutorial. I have a question. Why do we need to remove the eventlistener?

  • @a_l_o_k_1991
    @a_l_o_k_1991 3 года назад +1

    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 года назад +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.

  • @moeinmnia
    @moeinmnia Год назад

    thank you very much❤❤

  • @Zbaz10an
    @Zbaz10an 2 года назад

    Legend.👌

  • @AzizKhan-or8yp
    @AzizKhan-or8yp 2 года назад

    thank you soo much, worked

  • @ImpendingSole13
    @ImpendingSole13 4 года назад

    Thank you so much. It helped

  • @77thoughts
    @77thoughts 4 года назад

    Thanks, I like your style... :)

  • @adeshgangwar3555
    @adeshgangwar3555 3 года назад +1

    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 года назад +1

      No need to make a helper function. You can export the hook to share it between multiple components.

  • @raba650
    @raba650 4 года назад

    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.

  • @mohamedyoussef8835
    @mohamedyoussef8835 2 года назад

    Awesome explanation +++++++++++++++++++++++++++++ Thank You

  • @chandramanikandan3594
    @chandramanikandan3594 3 года назад

    Thank you it helped me lot

  • @theexplored
    @theexplored 3 года назад

    thank you ❤❤

  • @olegmaz3969
    @olegmaz3969 3 года назад

    Thanks a lot!

  • @wenderaugustovega214
    @wenderaugustovega214 2 года назад

    Vim de outro pais dizer que amei o vídeo.

  • @thanosav6507
    @thanosav6507 3 года назад

    Please help.
    Everything works but if i click my menu button again the hook triggers and it closes the menu BUT the button triggers and it opens again.
    So im stack with an open menu that closes only if i click outside the menu AND outside the menu button. What should i do?

    • @siddhant3852
      @siddhant3852 2 года назад

      did you find the solution?

    • @thanosav6507
      @thanosav6507 2 года назад

      @@siddhant3852 i dont remember exactly what i did but i think i removed the button listener when the menu was open. Then if i clicked the button it would just fire the hook to close the menu and when the menu was closed i would add te listener again.

  • @nwekarmahdi9211
    @nwekarmahdi9211 4 года назад

    well explained thanks.

  • @sanjibdey01
    @sanjibdey01 3 года назад

    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.

  • @thankgodokpara2156
    @thankgodokpara2156 4 года назад

    thank you for this

  • @hackhunter854
    @hackhunter854 2 года назад

    Great it worked

  • @vadykk
    @vadykk 4 года назад

    awesome !!! thank you so much.

  • @siddhant3852
    @siddhant3852 2 года назад

    problem: when I click button to close, the state becomes true again , because of it I can't toggle open and close. any possible solution for this?

    • @siddhant3852
      @siddhant3852 2 года назад

      using "click" instead of "mousedown" solves the problem.

  • @tabitasimorangkir3754
    @tabitasimorangkir3754 3 года назад

    Hey can someone help me, I did my code precisely the same as this tutorial but in my case, the click-outside-to-close didn't work. I assume it is because the "contains" property doesn't exist? I don't even know what it means please help!

    • @tabitasimorangkir3754
      @tabitasimorangkir3754 3 года назад

      const [showDropdownOne ,setShowDropdownOne] = useState(false);
      const domNode = useRef();

      useEffect(() => {
      document.addEventListener("mousedown", (e) => {
      if(domNode.current && !domNode.current.contains(e.target)){
      setShowDropdownOne(false);
      }
      });
      });
      and I did referenced 'domNode' in my dropdown tag, please somebody enlighten me if my code is wrong

  • @esmaeilmirzaee
    @esmaeilmirzaee 3 года назад

    Stupendous

  • @sarvagya-sharma
    @sarvagya-sharma 3 года назад

    Amazing!

  • @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 года назад +1

      Hi Hamidur! It's the Mac OSX screen shot tool (cmd+shift+4).

    • @iamHamidur
      @iamHamidur 3 года назад

      @@RyanToronto Thanks Ryan

  • @bimalskumar1464
    @bimalskumar1464 3 года назад

    Thank you :)

  • @azeemsultan7069
    @azeemsultan7069 3 года назад

    Thanks buddy

  • @pinjandarm
    @pinjandarm 4 года назад

    Thanks!

  • @aljimsonmegrino9580
    @aljimsonmegrino9580 4 года назад

    thank u very much

  • @vanoop729
    @vanoop729 3 года назад +1

    NIce

  • @saadbelghiti8150
    @saadbelghiti8150 2 года назад

    ty bro