Can't access component method after exporting by connect in React redux

46 Views Asked by At

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.

2

There are 2 best solutions below

0
Malkhazi Dartsmelidze On

ref={callback} syntax accepts a callback that is called with argument of type HtmlElement .

For example:

<div ref={divElement => window.divElement = divElement}>
  Test Ref
</div>

So, when you are calling: window.reactContactListContainer.renderContacts() it will throw an error, since window.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

0
Drew Reese On

The connect Higher Order Component needs to forward any passed React ref. It doesn't do this automatically so you will need to specify/configure connect to do this.

See options

options is the fourth argument passed to connect.

class ContactList extends Component {

  // props for contact

  renderContacts = () => {
    return // something
  };

  render() {
    return (
      <>
        // something
      </>
    );
  }
}

const mapStateToProps = state => ({ contacts: state.contacts })

export default connect(mapStateToProps, null, null, { forwardRef: true })(ContactList);

Edit cant-access-component-method-after-exporting-by-connect-in-react-redux

Note/Warning

This said, in addition to using really old "legacy" Redux code (current standard is to use React function components and the useDispatch and useSelector hooks with React.forwardRef and React.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.