I'm early in my own education of useRef and useImperativeHandle, but here's my understanding of it.
It's hard to tell from the code provided in your question how the components are setup, but it sounds like you want to call a method from a nested child component. Meaning you have a
Parent > Middle > Child
component structure, and want to call a method from Child in Parent.
To do this, you can pass the ref through the Middle component to the Child allowing the Child method to be called in the Parent.
However, it seems this could be handled in a simpler, easier to understand way - for example, using Redux, or passing a function to the child as a prop. Without seeing your full code it's hard to make recommendations.
Here's a simplified demo:
const Child = React.forwardRef((props, ref) => {
const buttonRef = React.useRef();
const handleClick = (event) => {
console.log('button click')
}
const childStyle = {
margin: 20
}
React.useImperativeHandle(ref, () => ({
click: () => {
buttonRef.current.click()
}
}))
return (
<button ref={buttonRef} style={childStyle} onClick={handleClick}>Child Component</button>
)
})
const Middle = ({childRef}) => {
const middleStyle = {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: 20,
backgroundColor: 'darkgray'
}
return (
<div style={middleStyle}>
Middle Component
<Child ref={childRef} />
</div>
)
}
const Parent = () => {
const childRef = React.useRef()
const parentStyle = {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
backgroundColor: 'lightgray',
padding: 20
}
const handleMouseEnter = () => {
/*
* CALL A METHOD FROM THE CHILD
*/
childRef.current.click()
}
return (
<div style={parentStyle} onMouseEnter={handleMouseEnter}>
<p>
Parent Component<br />
onMouseEnter of this gray area the onClick of the button will be called
</p>
<Middle childRef={childRef} />
</div>
)
}
ReactDOM.render(<Parent />, document.getElementById("app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
BaseMapfunctions fromZoneMapView? - Joseph D.useImperativeHandleworks, but that usinguseImperativeHandleto call another child refs doesn't. Are you trying to call a method from a Parent > Child > Child component? - Brett DeWoody