How would I go about redirecting to another react page with react-router@6
if conditions are not met? I was attempting to use this in the body of the component, but it doesn’t seem to do anything.
const Basket = () => {
redirect("/login")
return (
<div className="box">
<h2>Basket</h2>
</div>
);
}
export default Basket;
Bear in mind I haven’t yet programmed the if statement, but it will eventually look like this:
if (currentUser != null) {
<redirect here>
}
Could anyone point me in the right direction?
4
Answers
Here’s an example:
I’d prefer an
useEffect
approach, in casecurrentUser
is not defined or set in the first render.redirect
is a utility function only valid in RRDv6.4+ route loader and action functions. It’s not valid to call in a React component. If you want to issue a redirect from the UI you can use either theuseNavigate
hook (vianavigate
function) to issue an imperative redirect or render theNavigate
component for a declarative redirect.Imperative Redirect
Declarative Redirect
Suggestion
Instead of checking the user’s authentication status in the routed components it likely preferable to implement protected routes instead.
Example:
Then wrap the sets of routes you want to protect.
If you want to archieve that if the User is not LoggedIn use:
Pure React:
For the Next.js (React Framework):
useEffect() hook with useRouter(). Try something like this: