I just tried to use forwardRef with a withRouter(mycomponent) like this :
export default function App() {
const childRef = useRef();
const childWithRouteRef = useRef();
useEffect(()=>{
console.log("childWithRouteRef",childWithRouteRef);
childRef.current.say();
childWithRouteRef.current.say();
})
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<BrowserRouter>
<Child ref={childRef}/>
<ChildWithRoute_ ref={childWithRouteRef}/>
</BrowserRouter>
</div>
);
}
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
say: () => {
console.log("hello")
},
}));
return <div>Child</div>
})
const ChildWithRoute = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
say: () => {
console.log("hello")
},
}));
return <div>ChildWithRoute</div>
})
const ChildWithRoute_ = withRouter(ChildWithRoute)
if I wrapped my component in a withRouter HOC, the ref will not working, it's always null. so how can I use forwardRef with a component wrapped in withRouter?