Reputation: 2135
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.
Upvotes: 0
Views: 2144
Reputation: 202761
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
.
forwardedRef
, to 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.
Upvotes: 1