Search code examples
javascriptreactjsback-buttonreact-router-v4

Browser back button can not navigate in React Router v4


my problem is as in the title. I am using react v16 and react-router v4 I navigate to couple of pages after that i click on the browser back button. It takes me to last visited page not the last route that i navigated. In my previous react project (react v15, react-router v3) it is working just great. Here is my source code, please tell me my mistake. Thank you.

index.js

import { HashRouter as Router } from 'react-router-dom';
import routes from 'routes/index';

render(
<Provider store={store}>
    <div>
        <Router children={routes}/>
        <ReduxToastr
            timeOut={2000}
            newestOnTop={false}
            preventDuplicates={false}
            position="top-right"
            transitionIn="fadeIn"
            transitionOut="fadeOut"
            progressBar={false}
            showCloseButton={true}/>
    </div>
</Provider>, window.document.getElementById('app'));

routes.js

export default (
<Switch>
    <Route path="/login" component={Login} exact/>
    <Route path="/logout" component={Logout} exact/>
    <PrivateRoute path="/" component={Home} exact/>
    <PrivateRoute path="/home" component={Home}/>
    <PrivateRoute path="/apikeylist" component={ApiKeyList}/>
    <PrivateRoute path="/apikey/new" component={ApiKeyAddUpdate}/>
    <PrivateRoute path="/apikey/edit/:apiKey" component={ApiKeyAddUpdate}/>
    <PrivateRoute path="/etf/promoter" component={EtfPromoter}/>
    <PrivateRoute path="/etf/umbrella" component={EtfUmbrella}/>
    <PrivateRoute path="/etf/fund" component={EtfFund}/>
    <PrivateRoute path="/etf/shareclass" component={EtfShareclass}/>
    <PrivateRoute path="/index/indexvariant" component={IndexVariant}/>
</Switch>
);

PrivateRoute.js

import React from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router';
import App from 'layout/pages/App';
import { connect } from 'react-redux';
import Login from 'layout/pages/login';
import { withRouter } from 'react-router-dom';

class PrivateRoute extends React.Component {

constructor(props) {
    super(props);
}

render() {
    const { authenticated, component: Component, ...rest } = this.props;
    return (
        <Route {...rest} render={props => (
            authenticated ? (
                <App>
                    <Component {...props}/>
                </App>
            ) : (
                <Login/>
            )
        )}/>
    );
  }
}

PrivateRoute.propTypes = {
   authenticated: PropTypes.bool,
   component: PropTypes.any
};

const mapStateToProps = state => {
   return {
      authenticated: state.auth.authenticated
  };
};

export default withRouter(connect(mapStateToProps)(PrivateRoute));

Solution

  • Removed replace props from <NavLink/> and its works. replace attribute replaces your route with the current one. So it never keep the whole history only one route browser can remember. Solved.