Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
How to control react router using global JavaScript function like window object?

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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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;
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!