0

I know this issue has been discussed before. But, somehow I cannot get it work in my application.

Normally, the navigation works fine between components. However, history.push only changes the url but does not update the content. For example, in the Login page, I want to navigate user to Home page if already logged in. But, the code only updates the url. Any ideas?

const Login = () => {

    useEffect(() => {
        if (authenticationService.currentUserValue != null) {
            history.push('/home');
        }
    }, [])

    //other code
}

In index.js, I have the following

<BrowserRouter basename={baseUrl} history={history}>
    <Provider store={store}>
        <App />
    </Provider>
</BrowserRouter >,

In app.js, I have:

<Layout>
    <Switch>
        <PrivateRoute exact path="/home" component={withRouter(Home)} />
        <Route exact path='/home' component={withRouter(Home)} />
        <Route exact path='/login' component={Login} />
        <Route exact path='/register' component={withRouter(Register)} />
    </Switch>
</Layout>
5
  • Try rendering your App component as a default Route. Also you don't need to use withRouter with components Commented May 2, 2019 at 17:21
  • @ShubhamKhatri thanks for the comment. Could you please help me understand what does it mean rendering your App component as a default Route? Commented May 2, 2019 at 17:24
  • <Route component={App}/> Commented May 2, 2019 at 17:43
  • @ShubhamKhatri this crashes the page. Commented May 2, 2019 at 17:50
  • changing BrowserRouter to Router solves the problem. But, what if I want to use BrowserRouter? Or should I? Commented May 2, 2019 at 18:16

1 Answer 1

1

The issue in your case is that you are using a custom history with BrowserRouter which isn't correct. BrowserRouter uses its own history and you must use that to change pages

const Login = ({history}) => {

    useEffect(() => {
        if (authenticationService.currentUserValue != null) {
            history.push('/home');
        }
    }, [])

    //other code
}

If you have used custom history for a reason, then you need to use Router with a custom history prop

<Router basename={baseUrl} history={history}>
    <Provider store={store}>
        <App />
    </Provider>
</Router >
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.