React incorrectly detects ref children as a not children element with ref.current.contains()

Viewed 226

Hello I have problem with React ref detecting I have form which is render on Click and contain some checkboxes. Here is a form

  const [formVisibility, setFormVisibility] = useState(false)

  const ref = useRef(null)
  useClickOutsideRef({ ref, isVisible: formVisibility, onClickOutside: setFormVisibility(false) 
  })
  ///

  <div onClick=(() => setFormVisibility(!formVisibility))>
    Show Form
  </div>

  {formVisibility && <form>
     <div class='form' ref={ref}>
      <Checkbox {props} />
      <Checkbox {props} />
      <NewSelectComponent {props} />
      <button type='submit'>
       Save
      </button>
     </div>
    </form>}

I added function which close form when user click outside of this form

export function useClickOutsideRef ({ ref, isVisible, closeForm }: Props) {
  const handleClickOutside = (event: MouseEvent) => {
    if (ref.current && !ref.current.contains(event.target as Node) && isVisible) {
       closeForm()
    }
  }

  useEffect(() => {
    document.addEventListener('click', handleClickOutside)
    return () => {
      document.removeEventListener('click', handleClickOutside)
    }
  })
}

Since I added to it Select box from react-select library. Unexpected behavior started to occur =>

After click on any elements from select list, react don't recognize it as a descendant element of form and close form, but when clicks on any of other elements it's ok. So i guess that problem is in that react-select element When i console.log output of ref.current.contains(event.target) by clicking anywhere in the form it is true but when I click on any element of the list from react-select it's set to false!!! Why?

0 Answers
Related