disable back button in react-router 2

Viewed 38455

I am using react-router 2. My routes are defined as

   <Route path="/" component={App}>
       <IndexRoute component={Home}/>
       <Route path="/about" component={About}/>
       <Route path="/login" component={Login} onEnter={redirectToDashboard}/>
       <Route path="/logout" component={Logout} onEnter={logoutSession}/>
       <Route path="/dashboard" component={Dashboard} onEnter={redirectToLogin}/>
   </Route>

Everything working fine but I am having problem disabling back button from my dashboard page.

After successful login I am redirecting user to dashboard page but when user clicks back button it goes to login page again. I want to disable back button of browser when user is on dashboard page.

8 Answers

Applying all these hacks the URL changes to login for a moment and then to wherever-we-push. Instead, what we can do is: In login, where api endpoint returns success, do:

history.replace('/Whatever_screen')

This will remove login screen from window.history stack, and the screen will not flicker.

On your page which you want to disable back (example, on LoginApp ) add this block, to disable web history back

componentDidMount() {
    window.history.pushState(null, document.title, window.location.href);
    window.addEventListener('popstate', function (event){
        window.history.pushState(null, document.title,  window.location.href);
    });
}

in your login screen add replace to /dashboard

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory()

class LoginPage extends Component {
    componentDidMount(){
        history.replace({ pathname: '/dashboard' })
    }
    render() {
        const { history } = this.props
        return (
            <div>
            <h1>Login Page</h1>
            <button onClick={() => {
              login().then(() => {
                history.push('/dashboard')
              })
            }}>Login</button>
          </div>
        );
    }
}

export default withRouter(LoginPage);

The reason is replace your current path (/login) to /dashboard. Before adding this, please make sure you setup your authentication correctly.

It's not possible to disable browser buttons. But we can use history methods like listen(), go() and push() to override the default behaviour of back button in react.js. Also try to use withRouter().

The following is the sample code for doing this. Please look into componentDidMount() and componenetDidUnmount() methods.

import React from "react";
import { Redirect, Switch, Route, withRouter } from "react-router";

import Page1 from "./Page1";
import Page2 from "./Page2";
import Page3 from "./Page3";

class App extends React.Component {
  constructor(props) {
    super(props);

    // Store the previous pathname and search strings
    this.currentPathname = null;
    this.currentSearch = null;
  }

  componentDidMount() {
    const { history } = this.props;

    history.listen((newLocation, action) => {
      if (action === "PUSH") {
        if (
          newLocation.pathname !== this.currentPathname ||
          newLocation.search !== this.currentSearch
        ) {
          this.currentPathname = newLocation.pathname;
          this.currentSearch = newLocation.search;

          history.push({
            pathname: newLocation.pathname,
            search: newLocation.search
          });
        }
      } else {
        history.go(1);
      }
    });
  }

  componentWillUnmount() {
    window.onpopstate = null;
  }

  render() {
    return (
      <Switch>
        <Route exact path="/" render={() => <Redirect to="/page1" />} />
        <Route path="/page1" component={Page1} />
        <Route path="/page2" component={Page2} />
        <Route path="/page3" component={Page3} />
      </Switch>
    );
  }
}

export default withRouter(App);

For more: Disable react back button

In order to improve the code reusability, we can add an event listener in our index.html and dispatch the browser back disable event from all of our componentDidMount() methods.

In the index.html,

window.addEventListener('navigationhandler', function (e) {
  window.history.pushState(null, document.title, window.location.href);
  window.addEventListener('popstate', function (event) {
    window.history.pushState(null, document.title, window.location.href);
  });
});

In React componentDidMount() method,

componentDidMount() {
   window.dispatchEvent(new CustomEvent("navigationhandler"));
}
Related