1

I am using "connect" on the child component to interact with redux store(am using redux-toolkit). After importing the child component in parent component, I have created reference to the child component using createRef to access child component members.

Child component -->

class ChildComp extends React.Component<IReduxProps, IState>
{
}

default export connect(mapToState, mapToDispatch,null, { forwardRef: true })(ChildComp)

In parent component class

import ChildComp from './childCompFile'

class ParentComp extends React.Component<IReduxProps, IState> {
  childRef: React.RefObject<typeof ChildComp>;
  
  constructor(props: {}) {
    super(props);
    this.childRef= React.createRef<typeof ChildComp>();
  }
  
  onChildClick = () => {
    this.childRef.current.showChildCompPanel();
  };

  render() {
    <Button onClick={this.onChildClick}></Button>
    <ChildComp ref={this.childRef}/>
  }
}

Am not able to access any of the methods in child class using this.childRef.current. Please give an example to show how to access redux connected child class methods using ref from parent class

5
  • define the method at Parent instead, and pass down to Child. you don't pass methods upwards in React. Commented Jan 15, 2021 at 14:28
  • Yes the methods are used to change some state of child components like Show Panel state to turn on or off. Thats why its required Commented Jan 15, 2021 at 17:09
  • ChildComp is going to ignore the passed ref prop unless the ChildComp component is built to handle it using forwardRef and useImperativeHandle. You can do that, but it's probably better to move the show panel state up to ParentComp and pass it down through props. This explains the ref approach: stackoverflow.com/a/64491870/10431574 Commented Jan 15, 2021 at 21:12
  • If you can provide a repo or a codesandbox I can take a look at it. It's hard to see what's going awry from you've posted as there are some JSX errors and things that don't make sense to me, like why parent and child would have the same state interface. The link I previously posted deals with function components but you are using class components which does make ref forwarding easier. In its most basic version, your setup does work: codesandbox.io/s/eloquent-stallman-sfgj9?file=/src/App.tsx Commented Jan 15, 2021 at 21:36
  • 1
    @LindaPaiste IReduxProps, IState refers to just an example. It can be different for parent or child. Thanks any way. From your code I was able to figure out what I was doing wrong. Appreciated. Commented Jan 16, 2021 at 2:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.