Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Parent method in Child Component using Hook (ForwardRef concept)

I tried the following code but it fails So, this is my Parent Component:

    import React from 'react'
import ChildComponent from './ChildComponent';

const ParentComponent = (props) => {

    //step 1
    // const inputRef = React.createRef();
    const buttonRef = React.useRef();
    const focusHandler = () => {
        alert("hi");
    }

    return (
        <div>
            {/* In parent, we generally pass reference to child which we dint do here, lets see if props children help here */}
            {props.children}
            <ChildComponent ref="buttonRef" />

        </div>
    )
}

export default ParentComponent;

This is my child component:

import React from 'react'

const ChildComponent = React.forwardRef((props, ref) => {
    return (
        <div>
            <button onClick={ref.focusHandler}>Focus Input</button>      
        </div>
    )
})

export default ChildComponent;

On click of the button above in child component, I wish to call Parent method. How can that be achieved? EDITED

like image 292
sakshinarang Avatar asked Sep 19 '25 01:09

sakshinarang


1 Answers

The reason you're getting the error is because refs in function components need to be passed using ref={buttonRef}, not ref="buttonRef". Class components have a thing they can do with string refs, but it's not recommended even there.

As for calling a function from a parent component, you don't need refs to do this. So if that was the only reason you were using a ref, you can remove the ref. Instead, pass the function as a prop:

const ParentComponent = (props) => {
    const focusHandler = () => {
        alert("hi");
    }

    return (
        <div>
            <ChildComponent focusHandler={focusHandler} />
        </div>
    )
}

const ChildComponent = (props) => {
    return (
        <div>
            <button onClick={props.focusHandler}>Focus Input</button>      
        </div>
    )
}
like image 195
Nicholas Tower Avatar answered Sep 20 '25 18:09

Nicholas Tower