Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda