I have a React class component that has a method that I want to access later by using the provider. Below is the class
class ContactList extends Component {
// props for contact
renderContacts = () => {
return // something
};
render() {
return (
<>
// something
</>
);
}
}
const mapStateToProps = state => ({ contacts: state.contacts })
export default connect(mapStateToProps)(ContactList);
I have another component where I am using Provider and want to access methods of ContactList, but I am not able to access it. Below is the block which I am using with the provider.
<Provider store={GridStore}>
<ContactList
ref={component => {
window.reactContactListContainer = component
}}
/>
</Provider>
When I try to do window.reactContactListContainer.renderContacts(), it is not able to find that method.
ref={callback}syntax accepts a callback that is called with argument of typeHtmlElement.For example:
So, when you are calling:
window.reactContactListContainer.renderContacts()it will throw an error, sincewindow.reactContactListContaineris referencing to html element, not component itself.If you want to call child function from parent, you have to use Context or some other approach
See more about ref callbacks in react docs here