0

I'm struggling with redirecting / pushing history from the browser router component. Below is a broken down example of my app.

I have the state object (with user login data) along side the router component, for simplicity, in the example below this is a simple redirect in state.

If a user is logged in I want to redirect, but I get

Error Uncaught TypeError: Cannot read property 'history' of undefined and cant see how to access the history from this context.

inside components I can use this.context.router.history.push('/Welcome'); without issue, but this too doesn't work in the router component.

    import React from 'react';
import Header from './Header';
import Welcome from './Welcome';
import LoggedOut from './LoggedOut';
import { BrowserRouter, Route, Switch, Link, BrowserHistory  } from 'react-router-dom'


class Router extends React.Component{

    constructor(){
        super();
        this.state = {
            redirect: true,
        };

    }
    componentWillMount(){
        if(this.state.redirect){
            this.BrowserHistory.history.push('/logged-out'); // ⬅️ **This**
        }
    }

    render (){
        return(
            <BrowserRouter history={BrowserHistory}>
                <div>
                    <Header/>
                    <Switch>
                        <Route exact path="/" component={()=><Welcome />}/>
                        <Route path="/logged-out" component={()=><LoggedOut />}/>
                    </Switch>
                </div>
            </BrowserRouter>
            )
    }

}

Router.propTypes = {
    appMode:React.PropTypes.string.isRequired
}

export default Router;
Ash
  • 228
  • 6
  • 21

0 Answers0