I have this parent class component
class TransferHolder extends Component {
constructor(props) {
super(props);
this.transfer = React.createRef();
}
render() {
return (
<div>
<h1>HELLO !</h1>
<Transfer ref={this.transfer}/>
<Button onClick={() => {
const TransferRef = this.transfer.current;
console.log('Selected: ',
TransferRef.state.projectForm.users.right)
}}>
Print
</Button>
</div>
)
}
}
const mapStateToProps = state => {
return {
};
};
const mapDispatchToProps = dispatch => {
return {
};
};
export default connect(mapStateToProps, mapDispatchToProps)(TransferHolder);
When I visit the page an error is shown automatically that says:
index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `TransferHolder`.
in ConnectFunction (at TransferHolder.js:19)
in div (at TransferHolder.js:17)
in TransferHolder (created by ConnectFunction)
in ConnectFunction (created by Context.Consumer)
in Content (at ContentRoute.js:23)
I just want to access the state of the <Transfer>
Component which is a class based Component. However it is also wrapped in redux connect() so I don't know if that does convert it to a functional one.
Let's say the code for your component
Transfer
looks like this:If you use this component like above as
it will fail with the mentioned error message
because normal function components can not handle refs by default. To avoid that error, you have to wrap your component in forwardRef: