I'm using navigate(-1, { replace: true }); for login redirection. I want to check if previous route exists otherwise if previous route does no exist, navigate(-1) is not working good.
How can I check that?
I'm using navigate(-1, { replace: true }); for login redirection. I want to check if previous route exists otherwise if previous route does no exist, navigate(-1) is not working good.
How can I check that?
Better to use
navigate("Your login pathName", { replace: true });
For Example
navigate('/login',{ replace: true })
If I understand your question correctly, you are asking how to redirect a user back to a route they were attempting to access prior to authenticating. It's not really about trying to issue a back navigation, but rather, knowing you came from somewhere and you need to get back to that location.
The solution for this is generally to forward a "from" path, or referrer when redirecting to the login path/component so it can redirect back to the original path.
Here's an example showing the entire UI/UX flow you likely want to achieve. It starts with a specialized route component that grabs the current location and passes that with the redirect to the login route.
import { Navigate, Outlet } from 'react-router-dom';
const PrivateRoutes = () => {
const location = useLocation(); // <-- gets current location
const { isAuthenticated } = /* some auth state accessor */;
return isAuthenticated
? <Outlet />
: (
<Navigate
to="/login"
replace
state={{ from: location }} // <-- pass location in state
/>
);
}
And some protected/unprotected routes.
<BrowserRouter>
<Routes>
<Route path="/" element={<PrivateRoutes />} >
<Route path="/protected" element={<Protected />} />
</Route>
<Route path="/login" element={<Login />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
</BrowserRouter>
The Login component then handles the authentication flow, and upon successful login, then attempts to redirect back to this target path. Here's where you also provide a fallback path, usually "/", if there is no referrer value.
export default function Login() {
const location = useLocation();
const navigate = useNavigate();
const { login } = /* some auth state accessor */;
... local state
const loginHandler = async () => {
const isAuthenticated = await login(....);
if (isAuthenticated) {
// destructure referrer path or use fallback
const { from } = location.state || { from: { pathname: "/" } };
// redirect back
navigate(from, { replace: true });
}
};
return (
<div
style={{ height: "100vh" }}
className="d-flex justify-content-center align-items-center"
>
<button type="button" onClick={loginHandler} className="btn btn-primary">
Login
</button>
</div>
);
}