I want to be able to perform:
router.push('/compose')
And if not logged user will be redirected to the login page and from there to /compose. I'll be happy to learn a generic React solution or a specific Ant Design Pro solution. I know that And Design Pro have AuthorizedRoute but I don't know if it can allow this.
I'm using react-router 4.3.1 and antd 3.23.6.
Thanks
EDIT:
It probably needs to be something like @tyler-mcginnin answer:
function PrivateRoute ({component: Component, authed, ...rest}) {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}
I use React-router and then a conditional to do that. If I had a isAuthenticated variable, set to either true or false, passed into props it would look like this:
let routes = (//unauthenticated routes
<Switch>
<Route path = "/auth" component = {Auth} />
<Redirect to = "/auth" />
</Switch>
)
if(props.isAuthenticated){ //authenticated routes
routes = (
<Switch>
<Route path = "/manager" component = {DataManager} />
<Route path = "/logout" component = {Logout} />
<Redirect to = "/visualiser" />
</Switch>
)
}
Update based on comments:
Then in your auth component make a variable that sets the authRediect variable and then render that in your JSX. Something like this:
// This sets up a <Redirect> component so that if the state isAuthenticated is true it will not show the /auth page and isntead will redirect to the desired component:
let authRedirect = null;
if (props.isAuthenticated) {
authRedirect = <Redirect to = "/visualiser" />
};
...
return(
<React.Fragment>
{/*The line below performs an auth redirect if the user is authenticated*/}
{authRedirect}
<h1>Welcome </h1>
</React.Fragment>
);
So basically you just return the authRedirect variable conditionally based on whether your state is set to an authenticated state or not.