'using Ref on an HOC class component in react is null

When trying to use a ref I set on an instance of a class component, it's always null, and I can't see what I'm missing...

Component:

class MyComponent extends React.PureComponent {
    doSomething() {
       alert('huzzah!');
    }

    render() {
       return <div />;
    }
}

function myComponentWrapper(WrappedComponent) {
  class MyComponentWrapper extends React.PureComponent {
    static propTypes = {
      forwardedRef: PropTypes.object,
    };

    render() {
      const { forwardedRef, ...rest } = this.props;
      return <WrappedComponent {...rest} ref={forwardedRef} />;
    }
  }

  return React.forwardRef((props, ref) => <MyComponentWrapper {...props} forwardedRef={ref} />);
}

export default myComponentWrapper(MyComponent);

Parent side:

export default class MyParent extends React.PureComponent {
   render() {
       return (
          <div>
             <Button onClick={() => this.myRef.doSomething()}>Test</Button> // this.myRef is always null
             <MyComponent ref={(ref) => { this.myRef = ref; }} />
          </div>
       );
    }
}

I tried setting a ref using React.createRef, setting the ref not in a callback, and calling this.myRef.current.doSomething(), same result.

Also, trying to make the end goal for MyComponent to be a bit more complex by having MyComponent be:

import { connect } from 'react-redux';
import { compose } from 'redux';
import { connectRequest } from 'redux-query';
...
const component = compose(
  connect(mapStateToProps, null, null, { forwardRef: true }),
  connectRequest(mapPropsToConfig),
)(MyComponent);

But I'm not even getting the simple case to run (and I know something needs to be done to make the compose component pass the ref, but I don't know what that is either.

Appreciate the help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source