miladjurablu
miladjurablu

Reputation: 93

How to call child function from Parent react hook

in my parent component I have a dialog, and in Content of the dialog I load the child component

and this is the Dialog in parent component

<Dialog
    open={open}
    onClose={handleClose}
>
    <DialogContent>
        <DialogContentText >
            <Child id={id} status={status}/>
        </DialogContentText>
    </DialogContent>
    <DialogActions>
        <Button onClick={handleClose} />
        <Button onClick={handleAcceptClose} />
    </DialogActions>
</Dialog>

and in my child component I have sayhi method

const sayhi = () => {
    alert("sialaaaaaam");
}

How can I call the sayhi using ref, I want to use ref because I want a minimum render

Upvotes: 1

Views: 718

Answers (1)

Drew Reese
Drew Reese

Reputation: 202638

You'll need to forward a ref to the child component, and use the useImperativeHandle hook.

Example Child component:

const Child = React.forwardRef(
  (props, ref) => {
    const innerRef = React.useRef();

    const sayhi = () => alert("sialaaaaaam");

    useImperativeHandle(ref, () => ({
      sayhi,
    }));

    return (
      {/* Child JSX */}
    );   
  }
);

Then in the parent component create and attach a ref to Child:

const childRef = React.useRef();

...

<Child ref={childRef} id={id} status={status}/>

And to call the sayhi function:

childRef.current.sayhi();

Upvotes: 1

Related Questions