Home > other >  How to have a React child component call a function from a parent component
How to have a React child component call a function from a parent component

Time:02-11

I have a parent component and a child component (as a separate component file). How would I go about calling a function in the parent component from the child component?

The child component is imported into the parent component and the parent component has a function that makes an API call. I would like the child component to be able to also reach into the parent and run the api call function.

I could post the code I have but it's simply making an API call in the parent and having the child component imported in the parent.

thanks for any help.

CodePudding user response:

Provide the function as a property on the child element:

const Parent = () => {
  const someFunction = () => { /*...*/ };

  return <Child someProp={someFunction}/>;
}

const Child = ({ someProp }) => {
  return (
    <div onClick={() => someProp()}>
      Hello World
    </div>
  );
}
  • Related