AlwaysQuestioning
AlwaysQuestioning

Reputation: 1484

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)

Upvotes: 4

Views: 6340

Answers (2)

Dominik
Dominik

Reputation: 6313

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>
  );
}

Upvotes: 4

Bafsky
Bafsky

Reputation: 771

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

Upvotes: -2

Related Questions