Reputation: 111
I created protected route component that, if not authenticated, will redirect to '/' which is login. And that works fine. My question is how can I restrict path '/' if user is authenticated.
Eg. I want to go to '/welcome'
and i click on some external link that sends me to '/welcome'
but as I am not authenticated it redirects me to '/'
where I authenticate. After I finished authenticating it should redirect me to '/welcome'
again, my initial path.
How? I do now want to hard code path, I want to send me to the path that I was initially on.
If I change the path manually in browser to '/welcome'
, if I press back button it brings me back to '/'
and I do not want that. It should stay on '/welcome'
given that I am authenticated.
I have tried something like this:
<Route exact path="/">
{isAuth ? <Redirect to="/welcome" /> : <Auth />}
</Route>
The thing is that I do not want to hard code redirect to '/welcome' because maybe I came from another path '/example'
for example.
Any suggestions?
Upvotes: 1
Views: 51
Reputation: 2743
Try doing something like this.
const PrivateRoute = ({ component: Component, isLoggedIn, ...rest }) => (
<Route
{...rest}
render={props =>
isLoggedIn ? (
<Component {...props} />
) : (
<Redirect
to={{ pathname: '/', state: { from: props.location } }}
/>
)
}
/>
);
And then in your login component once authentication is done do the following while redirecting. If the pathName is present then it will go from where it came else it will redirect to /dash
in my case.
<Redirect
to={
this.props.location.state && this.props.location.state.from.pathname
? this.props.location.state.from.pathname
: "/dash"
}
/>
I'm using the Protected Route inside router as
<PrivateRoute
path="/someEndpoint"
component={SideMenu}
isLoggedIn={props.isLoggedIn}
/>
I hope I'm able to help you.
Upvotes: 2