Ref response on non-method-affected component
I am using ref on a component to force a filter form reset from its parent.
In the same component, we have:
handleFilterReset() {
// this.filterForm is defined but reset() isn't exposed
// see console.log(this.filterForm) output below
this.filterForm.reset()
}
render() {
return (
<FilterBox onReset={::this.handleFilterReset}>
<FilterForm ref={(ref) => { this.filterForm = ref }} />
</FilterBox>
)
}
And in FilterForm we have:
class FilterForm extends React.Component {
reset() {
// this is not being called
}
}
console.log output:
ProxyComponent {props: Object, context: Object, refs: Object, updater: Object, _reactInternalInstance: ReactCompositeComponentWrapper ...}
It seems to me that everything is done in accordance with the official documents. However, I am getting the following error:
Uncaught TypeError: this.filterForm.reset is not a function
at SalesChannelsList.handleFilterReset
thank
source to share
Found! It was "because" from React Intl.
1) Use withRef parameter to true when using injectIntl:
injectIntl(SalesChannelsFilterForm, { withRef: true })
2) In the ref callback of your component, you can access your instance with the following code
ref={(ref) => this.filterForm = ref.refs.wrappedInstance}
However, this will crash because the ref callback is called twice during render (), the first time with a null value. Therefore, you should first of all make sure that it is defined. My complete solution:
In the render () method on the component:
ref={::this.setFilterFormRef}
Then the handler:
setFilterFormRef(ref) {
if (ref && ref.refs) {
this.filterForm = ref.refs.wrappedInstance
}
}
Enjoy!
source to share