I know about the navigate hook but I need to control the route from window object that means it has to be a global function. In vuejs, it was easy like,
window.pushpath = function(path) { router.push("/"+path) }
how can i achieve this kind of behaviour in react? I cant use react hooks in js as it is forbidden to use react hooks without using it inside component.
A trivial solution could be to use a useEffect hook to set the window.pushpath function using the navigate function returned from the useNavigate hook.
Example:
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
useEffect(() => {
window.pushpath = function(path, options) {
navigate(path, options);
}
}, []);
This logic can only work so long as there is a router component higher in the ReactTree than the component running this effect, i.e. the Router must be in the parent component or higher.
Any linters may also complain about a missing dependency on the navigate function. It is, AFAIK, a stable reference, but should be ok to add.
useEffect(() => {
window.pushpath = function(path, options) {
navigate(path, options);
}
}, [navigate]);
Now that window.pushpath is updated, it can be called and passed the same arguments as the navigate function.
interface NavigateFunction { ( to: To, options?: { replace?: boolean; state?: any } ): void; (delta: number): void; }