Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda