Call a function from parent in React
From Logic Wiki
In the child component
import {forwardRef, useImperativeHandle} from "react";
wrap component like this
const SalesOrderGrid = forwardRef((props, ref) => {
}
So the component name is SalesOrderGrid in this example.
for the function we want to access (splitCash) from parent should be like
useImperativeHandle(ref, () => ({
splitCash(){
console.log("Cash split")
}
}))
if there are more then one function
useImperativeHandle(ref, () => ({
splitCash(){
console.log("Cash split")
},
test(){
console.log("test")
},
}))
In Parent
import {useRef} from "react";
Then
const orderGridRef = useRef();
then
<SalesOrderGrid ref={orderGridRef} />
and trigger should be
<Button variant="primary" className="m-2" onClick={()=> orderGridRef.current.splitCash()}>
Cash Split
</Button>