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

Sometimes, we want to use React.forwardRef in a class based component.

In this article, we’ll look at how to use React.forwardRef in a class based component.

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

To use React.forwardRef in a class based component, we render the class component in the forwardRef callback.

For instance, we write

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} />
));

to call forwardRef with a callback that renders the ElemComponent class component.

We set the innerRef prop to ref.

And then we access the ref with this.props.innerRef.

Conclusion

To use React.forwardRef in a class based component, we render the class component in the forwardRef callback.