0

I have a parent functonal component:

const parentFunc = () => {
  if (ref.current) {
   ref.current.getKinList();
  }
 };

<TouchableOpacity
onPress={() => {parentFunc()}
>
  <Text>click</Text>
</TouchableOpacity>

<ChildComponent
  ref={ref}
/>

child class component:

componentDidMount = () => {
  this.ref = { current: { function2 : this.function2 } };
 };

function2 = () => {
  console.log('called from child');
 };

function2 is not getting called from parent component.

There are solutions available, but I am not able to figure out where I am going wrong.

When I consoled ref.current in parentFunc it is coming as undefined

pratteek shaurya
  • 850
  • 2
  • 12
  • 34
  • Based on the code you shared, it seems like you are not initializing ```ref``` correctly. Shouldn't you be using ```this.props.ref``` in place of ```this.ref = ...``` to make use of the ref object passed in from parent? – sushrut619 Aug 01 '22 at 16:30

1 Answers1

0

You can do something like this:

export default function App() {
  const actions = React.useRef({
    setMyAction: (f) => {
      actions.current.myAction = f;
    }
  });
  return (
    <div>
      <div onClick={() => actions.current.myAction()}>click</div>
      <ChildComponent actions={actions.current} />
    </div>
  );
}

const ChildComponent = ({ actions }) => {
  actions.setMyAction(() => {
    console.log("called from child");
  });
  return null;
};

Working example

Also keep in mind that ref is a special name, not a usual property.

Ivan Shumilin
  • 1,743
  • 3
  • 13
  • 18
  • inside `parentFunc`, there are other functionalities too, where will those be integrated in your answer – pratteek shaurya Aug 01 '22 at 16:58
  • @pratteekshaurya You can put `parentFunc` logic into an `actions` object or directly into `onClick` handler. It is not clear for me how `function2` and `getKinList` are related. – Ivan Shumilin Aug 01 '22 at 17:17