Reputation: 1465
Trying to make a call to component's function from its parent using ref. The component is connected to Redux. Using React ^16. Says that: TypeError: this.usersTable.getWrappedInstance is not a function
. See code sample below:
export default class Users extends Component {
constructor(props){
super(props)
this.usersTable = React.createRef()
}
render() {
return (
<div>
<button type="button"
onClick={this.usersTable.getWrappedInstance().onAddUser}>ADD NEW USER</button>
<UsersTable onRef={node => this.usersTable = node} />
</div>
)
}
}
class UsersTable extends Component {
componentDidMount() {
this.props.onRef(this)
}
onAddUser = () => {
// DO SMTH
}
}
export default connect(mapStateToProps, mapDispatchToProps, null, { withRef: true })(UsersTable)
Upvotes: 1
Views: 844
Reputation: 222603
this.usersTable.getWrappedInstance()
is eagerly evaluated on render before usersTable
ref was assigned.
Refs are mixed up. It's either React.createRef()
or custom onRef
, not both. The latter wouldn't need getWrappedInstance()
but requires props to be passed to wrapped component with mapping functions.
In case React.createRef()
is used, it's:
usersTable = React.createRef();
onButtonClick = () => {
this.usersTable.current.getWrappedInstance().onAddUser();
}
...
<button type="button" onClick={this.onButtonClick}>
ADD NEW USER
</button>
<UsersTable ref={this.usersTable} />
Upvotes: 4