I'm upgrading react router V5 application to react router v6. I have come across some snippet which I'm not able to convert to V6. I tried enough and looked at different solutions over internet but nothing seem to work for me.
Code that I want to convert to V6,
import React, { useRef, useEffect } from "react";
import { useHistory } from "react-router-dom";
export default () => {
const ref = useRef(null);
const history = useHistory(); // the browser history object
useEffect(() => {
const { onParentNavigate } = mount(ref.current, {
onNavigate: ({ pathname: nextPathname }) => {
const { pathname } = history.location;
if (pathname !== nextPathname) {
history.push(nextPathname); //<<<<< how to convert this to v6 ?
}
},
});
history.listen(onParentNavigate); //<<<<<< how to convert this to v6 ?
}, []);
return <div ref={ref} />;
};
MyVersion using V6
const ref = useRef(null);
// const navigation = useContext(UNSAFE_NavigationContext).navigator as BrowserHistory();
const navigate = useNavigate(); // V6
const location = useLocation(); // V6
useEffect(() => {
const { onParentNavigate } = dashboardMount(ref.current, {
onNavigate: (result: any) => {
const { pathname } = location;
if (pathname !== result.location.pathname) {
navigate(result.location.pathname, { replace: true }); // This is not throwing any error but not giving expected outcome
}
}
})
navigate(onParentNavigate); // This not throwing any error but not giving me expected outcome as well
}, []);
return <div ref={ref}></div>
Any pointer or solution will be highly appreciated !