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

124
Vistas
Go back react router, and detect if the history have no items to hide the button

I want to make a button for going back, I did the following:

const GoBackBtn = ()=>{
   const navigate = useNavigate()
   return (<button onClick={()=>navigate(-1)}> {'<='} </button>)
}

It works great, however, the problem is when I first visit the webpage where this component is placed on and I'm in the root:

http://localhost:3000/

the problem which happens is when you click on the button, it takes you out of the website to the blank page (the browser home page, if you're using chrome, the home page of chrome).

I want to prevent that by hiding the button if there were no items in the history of the router.

But how I can detect that?

  • React router v6
  • React v18

I want to keep this functionality only on my website, I don't want it to navigate outside my website or to others websites

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

React Router has a hook called useLocation. Using this hook, you can get the path of the current route. The path for the root route is /.

I would add the condition such as:

import { useLocation, useNavigate } from 'react-router-dom'

const goBackBtn = () => {
  const location = useLocation()
  const navigate = useNavigate()

  const goBack = () => {
    if (location.pathname !== '/') {
      navigate(-1)
    }
  }

  return (
    <div>
      {location.pathname !== '/' && (
        <button onClick={goBack}>
          {'<='}
        </button>
      )}
    </div>
  )
}

about 4 years ago · Juan Pablo Isaza 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