React - useRef with TypeScript and functional component
You require to extract the ref type elsewhere:
interface RefObject {
SayHi: () => void
}
then just refer to it in both places
const Child = forwardRef((props: {name: string}, ref: Ref<RefObject>)=> {
const {name} = props;
useImperativeHandle(ref, () => ({ SayHi }));
function SayHi() { console.log("Hello " + name); }
return <div>{name}</div>;
});
const Parent = () => {
const ref = useRef<RefObject>(null);
const onButtonClick = () => {
if (ref.current) {
ref.current.SayHi();
}
};
return (
<div>
<Child name="Adam" ref={ref}/>
<button onClick={onButtonClick}>Log console</button>
</div>
);
}
Just replace the declaration of your ref
with this const ref = useRef<{ SayHi: () => void }>(null);