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?
I want to keep this functionality only on my website, I don't want it to navigate outside my website or to others websites
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>
)
}