Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a Parent function from a React functional component?

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)

like image 632
AlwaysQuestioning Avatar asked Sep 19 '25 10:09

AlwaysQuestioning


1 Answers

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>
  );
}
like image 137
Dominik Avatar answered Sep 21 '25 00:09

Dominik