Created
April 9, 2024 19:50
-
-
Save ernestofreyreg/f0fc6631105078ed7bd3341f7ba7ed0a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { forwardRef, useImperativeHandle, useRef } from 'react'; | |
const ChildComponent = forwardRef((props, ref) => { | |
useImperativeHandle(ref, () => ({ | |
handleAction() { | |
console.log('Action performed in Child'); | |
} | |
})); | |
return <div>Child Component</div>; | |
}); | |
function ParentComponent() { | |
const childRef = useRef(); | |
const callChildMethod = () => { | |
childRef.current.handleAction(); | |
}; | |
return ( | |
<div> | |
<button onClick={callChildMethod}>Call Child Method</button> | |
<ChildComponent ref={childRef} /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment