I need to call a function in a child component from a parent component with React Hooks.
I was trying to adapt this question to my use case React 16: Call children's function from parent when using hooks and functional component but I keep getting the error
TypeError: childRef.childFunction is not a function
My parent component is like this:
import React, { useRef, useEffect } from 'react';
import Child from './child'
function Parent() {
const parentRef = useRef()
const childRef = useRef()
const callChildFunction = () => {
childRef.current(childRef.childFunction())
}
useEffect(() => {
if (parentRef && childRef) {
callChildFunction();
}
}, [parentRef, childRef])
return (
<div ref={parentRef} className="parentContainer">
PARENT
<Child ref={childRef}/>
</div>
);
}
export default Parent;
My child component is like this:
import React, { forwardRef, useImperativeHandle } from 'react';
const Child = forwardRef(({ref}) => {
useImperativeHandle(ref, () => ({
childFunction() {
console.log("CHILD FUNCTION")
}
}));
return (
<div className="childContainer">
CHILD
</div>
);
})
export default Child;
What am I doing wrong?
imperative code using refs should be avoided in most cases. Why not elevate the state to the parent. or use redux or context hooks to pass values and functions between components?childRef.current(childRef.childFunction())- is this intentional? shouldn't you be callingchildRef.current.childFunction()directly?