DEV Community

Discussion on: 🔐 Private Route in React Router v6

Collapse
 
arknahian profile image
Al Nahian Ark

Ok, but how can I set a state and redirect the users from there they came from

Collapse
 
iamandrewluca profile image
Andrei Luca

You put some state in Navigation props, and on login after submit redirect back, something like this

function PrivateRoute() {
  const location = useLocation()
  return <Navigation to="/login" state={{ from: location.pathname }} />
}

function Login() {
  const navigate = useNavigate()
  const location = useLocation()

  const onSubmit = () => fetch("/api/login").then(() => navigate(location.state.from))

  return <form onSubmit={onSubmit} />
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
Sloan, the sloth mascot
Comment deleted
 
iamandrewluca profile image
Andrei Luca

You mean to prevent before user is clicking a link? 🤔 Didn't quite get what exactly do you mean.