Bogdan Daniel
Bogdan Daniel

Reputation: 2759

react-router-dom v4 Redirect to programatically

I have a UserLogin component which will send a request and upon response I want to redirect to the AfterLogin component.

if (xhr.status === 200) {
                // success
                this.context.history.push('/dashboard')
            }

After a lot of search my react-router-dom v4 Router looks like this:

import { BrowserRouter as Router, Route, Switch,Redirect} from 'react-router-dom'
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();

<Router forceRefresh={false} history={history}>
        <div>
            <Switch>
                <Route exact path="/" render={() => (
                    Auth.isUserAuthenticated() ? (
                        <DashboardPage/>
                    ) : (
                        <LoginPage/>
                    )
                )}/>
                <Route path="/dashboard" render={() => (
                    Auth.isUserAuthenticated() ? (
                        <DashboardPage/>
                    ) : (
                        <Redirect to="/login"/>
                    )
                )}/>
                <Route path="/login" render={() => (
                    Auth.isUserAuthenticated() ? (
                        <Redirect to="/dashboard"/>
                    ) : (
                        <LoginPage/>
                    )
                )}/>
                <Route path="*" component={Error}/>
            </Switch>
        </div>
    </Router>

Everything is working perfectly fine, except the this.context.history.push('/dashboard')part. How do I redirect the user after login? By using that method I see in the console that this.context is not defined.

Cannot read property 'push' of undefined

Upvotes: 0

Views: 1535

Answers (1)

pizzarob
pizzarob

Reputation: 12049

You need to specify which properties of context you want your component to have access to. Supposing your xhr request is inside your UserLogin component you will need to add the following to access context.history.

UserLogin.contextTypes = {
    history: React.PropTypes.object,
};

But you should not use context, rather you should use React Routers withRouter function which will put history on props of your component.

https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class UserLogin extends React.Component { ... }

// can call history with this.props.history in UserLogin now
export default withRouter(UserLogin);

Upvotes: 1

Related Questions