Just in case anyone gets here like I did trying to navigate back OR navigate somewhere else if you can't navigate back (e.g. link opened in new tab), there doesn't seem to be any way of verifying the history with react-router in v6. However it seems you can access window.history.state which has an idx property that is zero if you're at the start of the history stack.
It's possible there are some gotchas around it that I haven't hit up against, but it's working for me:
import { useNavigate } from 'react-router-dom';
// ...
const navigate = useNavigate();
// ...
if (window.history.state && window.history.state.idx > 0) {
navigate(-1);
} else {
navigate('/', { replace: true }); // the current entry in the history stack will be replaced with the new one with { replace: true }
}
import { useEffect } from "react";
import {useNavigate } from "react-router-dom";// react-router-dom v6 version
const SecondComponent = () =>{
const navigate = useNavigate();
useEffect(() => {
navigate('/secondComponent')
},[]);
// note: we must have to to provide path like this one
/*
<Routes>
<Route path="/" element={<FirstComponent/>} />
<Route path="/secondComponent" element={<SecondComponent />} />
</Routes>
*/
return(
<>
<h2 >this is Second page</h2>
</>
)
}
export default SecondComponent;