Home > front end >  how to call a function contained within a direct child component from the parent? (functional compon
how to call a function contained within a direct child component from the parent? (functional compon

Time:03-23

I am new to react. Basically I want that when I click on the button of the child component, the function myFunction is called from the parent component. How can I do it?

This is my live code

import "./styles.css";
export const Parent = ({ children }) => {
  //I need excecute myFunction when user click
  return (
    <div>
      I am parent <br />
      <br /> {children}
    </div>
  );
};
export const Child = () => {
  const myFunction = () => {
    console.log("say hello from parent");
  };
  return (
    <div>
      I am children
      <br />
      <button>Send function to execute in the parent</button>
    </div>
  );
};

export default function App() {
  return (
    <Parent>
      <Child />
    </Parent>
  );
}

CodePudding user response:

Try calling child inside parent function as shown below :

import "./styles.css";

export const Child = (props) => {
  const myFunction = () => {
    console.log("say hello from parent");
  };
  return (
    <div>
      I am children
      <br />
      <button onClick={props.randomFun}  >Send function to execute in the parent</button>
    </div>
  );
};

export const Parent = () => {
  //I need excecute myFunction when user click
  const handleChild=()=>{console.log("You clicked on child button")}
  return (
    <div>
      I am parent <br />
      <br /> 
      <child randomFun = {handleChild} />
    </div>
  );
};

export default function App() {
  return (
    <Parent />
  );
}

CodePudding user response:

you want this?

export const Child = () => {
   const myFunction = () => {
    console.log("say hello from parent");
  };
  return (
    <div>
      I am children
      <br />
      <button onClick={()=>myFunction()}>Send function to execute in the parent</button>
    </div>
  );
};

CodePudding user response:

We can use useRef,

Here we have a parent component with a button and a child component with a function to show an alert. If you want to call the showAlert function when the button is clicked, there is no direct way to access it.

import { forwardRef, useRef, useImperativeHandle } from "react"

const ChildComp = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    showAlert() {
      alert("Hello from Child Component")
    },
  }))
  return <div></div>
})

function App() {
  const childCompRef = useRef()
  return (
    <div>
      <button onClick={() => childCompRef.current.showAlert()}>Click Me</button>
      <ChildComp ref={childCompRef} />
    </div>
  )
}

export default App
  • Related