Skip to content

Instantly share code, notes, and snippets.

@ernestofreyreg
Created April 9, 2024 19:50
Show Gist options
  • Save ernestofreyreg/f0fc6631105078ed7bd3341f7ba7ed0a to your computer and use it in GitHub Desktop.
Save ernestofreyreg/f0fc6631105078ed7bd3341f7ba7ed0a to your computer and use it in GitHub Desktop.
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