4

I want my React functional component to call a function in its parent.

I was able to do this with class components like so:

<MyChild func={this.functionname} />

But I'm having trouble access this.functionName withtin my child component, which is a functional component.

How can I access this in the child functional component, *as well as within all of its functions (e.g. useCallback and useEffect)

AlwaysQuestioning
  • 1,464
  • 4
  • 24
  • 48

2 Answers2

4

I'm not sure I understand the question correctly but you can call a function from the parent component inside the child easily like so:

export function Child({ func }) {
  useEffect(() => {
    console.log('Calling func');
    func();
  }, [func]);

  return <div>I am the child component</div>;
}

export function Parent() {
  const childFunc = () => console.log('call me!');

  return (
    <main>
      <h1>Hello world</h1>

      <Child func={childFunc} />
    </main>
  );
}
Dominik
  • 6,078
  • 8
  • 37
  • 61
  • Thanks for this. To be specific, I'm trying to update a state variable in the parent function *twice* from the child. Once at the beginning of the child function, and once at the end. The state is only changing once, though. Any idea why? – AlwaysQuestioning May 13 '21 at 15:26
  • 1
    You're running a state function twice in the same function and expect the state to change mid-function? React can't divide your function and run only half of it so a function will run whole so if you make state changes inside the same function you will have to keep track of that yourself which should be straight forward – Dominik May 13 '21 at 22:06
-2

The method is accessed in your child component with this.props.func.

Bafsky
  • 761
  • 1
  • 7
  • 16