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.
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 forconnect
will only forward aref
to the wrapped component, in this caseChildComponent
. You instead want to actually "pass" a ref further and attach it to a child component ofChildComponent
.forwardedRef
, to child component.Parent Component
Child Component
Note: Since we aren't attaching a ref to
ParentComponent
andChildComponent
doesn't need it, it is unnecessary to specifyforwardRef: true
in theconnect
HOC config argument given the provided code example.