Friday, 12 May 2017

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



via Bogdan Daniel

No comments:

Post a Comment