react-router 4 doesn't update UI when clicking <Link>

I am writing a small app with a navigation bar and 5 routes using react-router-dom 4.1.1. When I click on a link in the navigation bar, the URL in the Firefox address bar updates, but the page displayed does not change. However, if I enter the address of a subpage in the address bar, the correct page is displayed.

app.js:

render(
    <Provider store={store}>
        <HashRouter>
            <MainContainer />
        </HashRouter>
    </Provider>,
    document.querySelector('.app')
);

Main.js:

render() {
    return (
        <div className="main">
            <Message message= {this.props.message} />
            <NavigationBar />
            <Switch>
                <Route exact path="/" component={HomePage}></Route>
                <Route path="/classify" component={ClassifyPage}></Route>
                <Route path="/admin" component={AdminPage}></Route>
                <Route path="/users" component={UsersPage}></Route>
                <Route path="/help" component={HelpPage}></Route>
            </Switch>
        </div>
    );
}

Answers:

Answer

It seems some components, like react-redux containers using connect(), block updates. The problem was solved using withRouter():

const MainContainer = withRouter(connect(
        mapStateToProps,
        mapDispatchToProps
      )(Main));

Documentation: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

Answer

I have the same error, but when I use withRouter, nothing changes. In my case, the reason of error is putting the <Link> elements into the <Router> tag.

<Router>
<Link to="something"></Link>
</Router>

Beware of that error, is very hard to diagnose! To fix this, just remove unneccesary <Router> wrapper

Answer

Erik Winge almost the right. As I understand component where you enter you need to wrap your Component with withRouter.

So, to fix this you need to add:

...
Main = withRouter(Main);
...
export default Main;
...

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.