How to use React forwardRef with react-redux in Class component?

2k views Asked by At

How can I use forwardRef in Class Component with the connect function of react-redux?

import React, { Component } from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends Component {
constructor(props) {
    super(props);
    this.myRef = React.createRef();
}

render() {
    return <ChildComponent ref={this.myRef} />;
}
}

export default ParentComponent;

Child Component

import React, { Component } from 'react';
import { TextInput } from 'react-native';
import { connect } from 'react-redux';
class ChildComponent extends Component {
render() {
    return <TextInput value={'Hi'} ref={??} />;
}
}

export default connect(null, null, null, { forwardRef: true })(ChildComponent);

I don't know how to use React.forwardRef() in Class Component.

1

There are 1 answers

0
Drew Reese On

The connect function is a Higher Order Component. You can follow the steps here in forwarding refs in higher order components to understand better how a HOC can forward a ref to a wrapped component.

The gist is that a react ref isn't a prop, it is special like react keys, but you can pass them as props when necessary. { forwardRef: true } option for connect will only forward a ref to the wrapped component, in this case ChildComponent. You instead want to actually "pass" a ref further and attach it to a child component of ChildComponent.

  1. Create ref in parent component.
  2. Pass the ref as a named prop, forwardedRef, to child component.
  3. (a) Destructure/access the named ref in child component and (b) attach to the inner child component.

Parent Component

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef(); // <-- (1)
  }

  render() {
    return <ChildComponent forwardedRef={this.myRef} />; // <-- (2)
  }
}

Child Component

class ChildComponent extends Component {
  render() {
    const { forwardedRef } = this.props; // <-- (3a)
    return <TextInput ref={forwardedRef} value={'Hi'} />; // <-- (3b)
  }
}

Note: Since we aren't attaching a ref to ParentComponent and ChildComponent doesn't need it, it is unnecessary to specify forwardRef: true in the connect HOC config argument given the provided code example.