title: React closing a dropdown when click outside
body: <p>Building a custom dropdown in React and came across a problem when trying to close it when clicking outside.<br />
  So i created generic HOC so i can use it for other ocasions as well.</p>
  <p>The problem i seem to have is i don't know hwo to pass the <code>ref</code> from the hoc to the component.</p>
  <p>I've been looking into <a href="https://reactjs.org/docs/forwarding-refs.html" rel="noreferrer">forwardRef</a> and other tones of examples, but i can't figure it out.<br />
  Any idea if it's possible and how i could do it?</p>
  <p><a href="https://codesandbox.io/s/react-withclickoutside-c95gt?file=/src/Home.js" rel="noreferrer">Codesandbox Demo</a></p>
  <pre><code>import React, { useState, useRef, useEffect } from &quot;react&quot;;
  
  export default function withClickOutside(WrappedComponent) {
    const Component = (props) =&gt; {
      const [open, setOpen] = useState(false);
  
      const ref = useRef();
  
      useEffect(() =&gt; {
        const handleClickOutside = (event) =&gt; {
          if (!ref?.current?.contains(event.target)) {
            setOpen(false);
          }
        };
        document.addEventListener(&quot;mousedown&quot;, handleClickOutside);
      }, [ref]);
  
      return &lt;WrappedComponent {...props} open={open} setOpen={setOpen} ref={ref}/&gt;;
    };
  
    return Component;
  }
  
  </code></pre>