How to use React.forwardRef in a class based component?

The idea to always use the same prop for the ref can be achieved by proxying class export with a helper.

class ElemComponent extends Component {
  render() {
    return (
      <div ref={this.props.innerRef}>
        Div has a ref
      </div>
    )
  }
}

export default React.forwardRef((props, ref) => <ElemComponent 
  innerRef={ref} {...props}
/>);

So basically, we are forced to have a different prop to forward ref, but it can be done under the hub. It’s important that the public use it as a normal ref.

Leave a Comment