The Code is written using React Functional components.
Upon clicking button in parent, the function showAlert should be fired. That is the requirement.
Currently in the parent component childRef.current is not able to call showAlert() function. I get a typescript error
Property 'showAlert' does not exist on type 'ForwardRefExoticComponent<RefAttributes<unknown>>'
Parent Functional component Code
import React, { forwardRef, useRef, useImperativeHandle } from 'react';
import Child from './Child';
export default function App() {
const childRef = useRef<typeof Child>(Child);
return (
<div className="container">
<Child ref={childRef} />
<button
onClick={() => { childRef.current.showAlert() }}
>
Call Function
</button>
</div>
)
}
Child Functional component
import React, { forwardRef, useRef, useImperativeHandle } from 'react';
const Child = forwardRef((props, ref) => {
useImperativeHandle(
ref,
() => ({
showAlert() {
alert("Child Function Called")
console.log('hello world')
}
}),
)
return (
<div>Child Component</div>
)
})
export default Child