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

275
Vistas
React: How to redirect to new route (different id) from same route?

In react-router, we cannot push the same route in useHisotry() and cause a re-render. E.g., if component App is showing on route https://localhost:3000 and I click the button Click Me!, it won't cause a re-render:

function App() {
   const history = useHistory();
   return (
      <button onClick={() => {history.push('/')}}> Click Me! </button>
   )
}

I want to achieve similar functionality, but I am unsure about the approach or what I am missing.

My current route looks like this: https://localhost:3000/user/1

I want to go to user/2 by clicking a button.

My code looks like the below:

<Route exact path="/user/:userId" component={User} />

function User() {
   const history = useHistory();
   return (
      <button onClick={() => {history.push('/user/2')}}> Click Me! </button>
   )
}

The above code changes the route but doesn't re-render the component. How can I fix this issue?

Thanks

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

My advice is to upgrade to react router dom v6 and use useNavigate , tutorial here

once you import useNavigate from react-router-dom

let navigate = useNavigate();

and on your button you call this function on click passing your desired url

<button onClick={()=> navigate('/users/2')}

Your component's info wont change because you arent rendering anything dynamically in it, so you should grab the userid from the url, and then lets say display it. Check Docs

As the answer below, you can do it exactly as he said.

const { userId } = useParams();
return (
    <div>userId: { userId }</div>
);
about 4 years ago · Santiago Trujillo Denunciar

0

I don't recommend using history for this case. If you really need to, inside User component get userId parameter and react on that.

<Route exact path='/user/:userId' component={User} />

const User = () => {
    const { userId } = useParams();
    return (
        <div>userId: { userId }</div>
    );
}
export default User;
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