Automatic redirect after login with react-router
ReactjsReactjs FluxReact RouterReactjs Problem Overview
I wanted to build a Facebook login into my react/react-router/flux application.
I have a listener registered on the login event and would like to redirect the user to '/dashboard'
if they are logged in. How can I do that? location.push
didn't work very well, except after reloading the page completely.
Reactjs Solutions
Solution 1 - Reactjs
> React Router v3
This is what I do
var Router = require('react-router');
Router.browserHistory.push('/somepath');
> React Router v4
Now we can use the <Redirect>
component in React Router v4.
Rendering a <Redirect>
will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects.
import React, { Component } from 'react';
import { Redirect } from 'react-router';
export default class LoginComponent extends Component {
render(){
if(this.state.isLoggedIn === true){
return (<Redirect to="/your/redirect/page" />);
}else{
return (<div>Login Please</div>);
}
}
}
Documentation <https://reacttraining.com/react-router/web/api/Redirect>
Solution 2 - Reactjs
> React Router v0.13
The Router
instance returned from Router.create
can be passed around (or, if inside a React component, you can get it from the context object), and contains methods like transitionTo
that you can use to transition to a new route.
Solution 3 - Reactjs
> React Router v2
Even though the question is already answered, I think it's relevant to post the solution that worked for me, since it wasn't covered in any of the solutions given here.
First, I'm using the router context on my LoginForm
component
LoginForm.contextTypes = {
router: React.PropTypes.object
};
After that, I can access the router
object inside my LoginForm
component
handleLogin() {
this.context.router.push('/anotherroute');
}
PS: working on React-router version 2.6.0
Solution 4 - Reactjs
> React Router v3
Navigating Outside of Components
create your app with Router like this
// Your main file that renders a <Router>:
import { Router, browserHistory } from 'react-router'
import routes from './app/routes'
render(
<Router history={browserHistory} routes={routes} />,
mountNode
)
Somewhere like a Redux middleware or Flux action:
import { browserHistory } from 'react-router'
// Go to /some/path.
browserHistory.push('/some/path')
// Go back to previous location.
browserHistory.goBack()
Solution 5 - Reactjs
> React Router v4.2.0
I am using React-16.2.0 & React-router-4.2.0
And I get solution by this code
this.props.history.push("/");
My working code:
.then(response => response.json())
.then(data => {
if(data.status == 200){
this.props.history.push("/");
console.log('Successfully Login');
}
})
I was following this document redirect-on-login-and-logout
I was also try by return <Redirect to='/' />
But unlucky, this not working for me.
Solution 6 - Reactjs
React router v5 using hooks
These steps are for authorisation redirect. But can be used for login/logout redirection also.
The <Redirect/>
accepts to
prop as a string or an object. We can utilise the object to pass the redirection path after login/logout using hooks easily.
-
Get the pathname of url from where the
<Redirect/>
is called usinguseLocation()
const {pathname} = useLocation()
-
In the
to
prop of<Redirect/>
pass in the following object:
<Redirect to={{pathname:'/login',state: {referrer: pathname}}/>
-
In the Login component access the route state variable using
useLocation()
hook and use theuseHistory()
hook to redirect after successful login.
const history = useHistory();
const location = useLocation();
const login() => {
// After login success
const {state: {referrer}} = location;
history.push(referrer)
};
Check the official docs here
Solution 7 - Reactjs
> React Router v3
Navigating inside components
You should use withRouter
decorator when it's necessary to redirect inside a component. The decorator uses context instead of you.
import {withRouter} from 'react-router'
fucntion Foo(props) {
props.router.push('/users/16');
}
export default withRouter(Foo);
> withRouter(Component, [options]) > > A HoC (higher-order component) that wraps another component to enhance > its props with router props. > withRouterProps = { ...componentProps, router, params, location, routes }
>Pass in your component and it will return the > wrapped component. > > You can explicit specify router as a prop to the wrapper component to > override the router object from context.
Solution 8 - Reactjs
In your store:
data.router.transitionTo('user');
And router has:
"Route name="user" handler={User}"
User is route handler