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

129
Views
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 answers
Answer question

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 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!