I currently have a parent component with 2 child components.
In the first child component there is a button and when I click that button I want to access a function that is inside the second child component.
I know a little about forwardRef, and how to access a child function from a parent component, but not from a child component.
I hope this makes sense. I have tried to search for docs on this, but all I see is the parent access child function and the other way around, but not from child component accessing another child function.
To add a bit of code:
import Child1 from './child1';
import Child2 from './child2';
const parent = () => {
const childRef = useRef();
return (
<Child1 onZoomHandler={childRef.current?.zoomHandler} />
<Child2 ref={childRef} />
)
}
export default parent;
#child 1
const child1 = (props) => {
const zoomHandler = () => {
props.onZoomHandler();
}
return (
<Button onClick={zoomHandler} />
)
}
export default child1;
#Child2
import { forwardRef, useImperativeHandle } from 'react';
const child2 = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
zoomHandler
}));
const zoomHandler =() => {
}
return (
<div ref={ref} />
)
}
export default child2;
The error I am getting is (on the first child):
props.onZoomHandler is not a function
2
Answers
When you render the
Parent
for the 1st time,childRef.current
isundefined
, so theonZoomHandler
value isundefined
.Updating the
childRef
inChild2
doesn’t cause a re-render, soonZoomHandler
staysundefined
.Instead declare a
zoomHandler
function inParent
, and pass it toChild1
. ThezoomHandler
calls the function in the ref when it’s called.It seems you’d like to trigger a function from a sibling component. This functionality can be achieved quite easily by utilising a fundamental concept in React known as "State Lifting." You can learn more about it here: https://react.dev/learn/sharing-state-between-components%5Benter link description here][1] .
To implement this solution, you’ll need to create a state in the parent component. Then, pass the state’s update function (usually setState) as a prop to the first component. By doing so, you can trigger your desired function within the first component, which, in turn, updates the state in the parent component. This updated state can then be passed as a prop to the second child component, enabling it to perform actions based on your specific requirements. This approach effectively facilitates communication and interaction between sibling components.