I want to call a child component's function in a parent component. Here's my pseudo-code:
export const Child: React.FC<Props> = ({ onRef }) => {
useEffect(() => {
if (onRef) {
onRef(this);
}
}, [])
function callMe() {
console.log('Child has been called');
}
return <Text>Child</Text>;
}
export const Parent: React.FC<Props> = () => {
const childRef = useRef(null);
function callChild() {
childRef.current.callMe();
}
return <Child onRef={childRef} />;
}
How do I do this?
You can use useImperativeHandle to call the child component function.
You can define your function like this in Child component.
useImperativeHandle(ref, () => ({
callMe: () => {
console.log('Child has been called');
}
}));
In addition, you should also apply forwardRef
to the child component:
export const Child = forwardRef(props, ref) => {
// component logic
});
Now you can call this function by creating a ref in the parent component like this:
const childRef = useRef(null);
function callChild() {
childRef.current.callMe();
}
return <Child ref={childRef} />;