I have a class 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.
2
Answers
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.reactContactListContainer
is 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
The
connect
Higher Order Component needs to forward any passed React ref. It doesn’t do this automatically so you will need to specify/configureconnect
to do this.See options
options
is the fourth argument passed toconnect
.Note/Warning
This said, in addition to using really old "legacy" Redux code (current standard is to use React function components and the
useDispatch
anduseSelector
hooks withReact.forwardRef
andReact.useImperativeHandle
) what you are trying to do here seems highly suspect and anti-pattern to established React design and usage. React components don’t reach into and invoke internal functions of other React components.Since whatever it is you really want to do is obfuscated in the
// something
I can’t speak more to what is a current and acceptable refactor.