title: React context consumer how to access ref on to the consuming component
body: <p>I've build a higher order component using the <a href="https://reactjs.org/docs/context.html" rel="nofollow noreferrer">new context API of React</a> and I am trying to to find a way to be able to access the reference (via <code>ref()</code>) of a wrapped child component.</p>
  
  <p><strong>tl/dr:</strong> Essentially I want to <a href="https://reactjs.org/docs/forwarding-refs.html" rel="nofollow noreferrer">forward the ref</a> from the <code>Consumer</code> to the actual component.</p>
  
  <p>Here's a specific example. The <code>RootComponent</code> sets the value for the <code>CoolProvider</code> that is suppose to be exposed on all <em>wrapped</em> child components. A child component is wrapped using <code>withCool()</code> such that it can access <code>props.cool</code>. (Of course in a real world example everything is much more complex and there are dozens of components.)</p>
  
  <p>Now independent of knowing whether a child component has been wrapped I would like to be able to get a reference to it via <code>ref()</code> as illustrated in <code>RootComponent</code> but unfortunately the wrapped components do not support <code>ref()</code> anymore as they are functional!</p>
  
  <p>Check out this live demo (<a href="https://jsfiddle.net/64t0oenz/3/" rel="nofollow noreferrer">https://jsfiddle.net/64t0oenz/3/</a>) and inspect the web console. You will see that only the callback for the non-wrapped component fires.</p>
  
  <p>My question is: is there a way to forward the reference request from the <code>CoolConsumer</code> to the actual component such that the parent component can access it's reference?</p>
  
  <pre><code>const { Provider: CoolProvider, Consumer: CoolConsumer } = React.createContext();
  
  const withCool = Component =&gt; props =&gt; (
    &lt;CoolConsumer&gt;
      {cool =&gt; &lt;Component {...props} cool={cool} /&gt;}
    &lt;/CoolConsumer&gt;
  );
  
  class ChildComponent extends React.Component {
    render() {
      return this.props.cool ? (
          &lt;div&gt;Isn't this cool?&lt;/div&gt;
      ) : (
        &lt;div&gt;Not so cool!&lt;/div&gt;
      );
    }
  }
  
  const CoolChildComponent = withCool(ChildComponent);
  
  class RootComponent extends React.Component {
    render() {
      return (
          &lt;CoolProvider value={true}&gt;
          &lt;ChildComponent ref={(c) =&gt; { console.log('Normal child ref', c); }}/&gt;
          &lt;CoolChildComponent ref={(c) =&gt; { console.log('Cool child ref', c); }}/&gt;
        &lt;/CoolProvider&gt;
      );
    }
  }
  
  ReactDOM.render(&lt;RootComponent /&gt;, document.querySelector('#cool'));
  </code></pre>