简体   繁体   中英

React detect click outside a component with custom hook

I'm trying to create a custom hook as I read in other StackOverflow responses, to detect a click outside the component. I'm not sure what I'm missing here but something is not working right. The event needs to be appended only to the checkbox dropdown menu so when the user is open the dropdown and clicking outside the menu it will automatically close itself. Although it looks like it works, you can notice that although the dropdown closed when the user clicks outside, it also prevents you from checkbox the input.

Check my code here: SandBox Any help will be greatly appreciated

I think it was just a typo. in your sandbox i fixed the handleClickOutside like this:

  const handleClickOutside = (event) => {
    console.log(event.target);
    if (ref.current && !ref.current.contains(event.target)) {
      setIsComponentVisible(false);
    }
  };

there was missing a "t" in the "target" in !ref.current.contains(event.target)

Is it working for you now?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM