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.
navigate
interface NavigateFunction {
(
to: To,
options?: { replace?: boolean; state?: any }
): void;
(delta: number): void;
}