disable back button in react-router 2
Asked Answered
D

10

17

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.

Dodson answered 21/3, 2016 at 20:58 Comment(0)
G
22

Your best bet, is when the user is login he/ she is redirected to dashbaord. if for some reason the user click on back button you should:

if the user is logged in stay on the page dashboard

if(logged) {
  history.pushState(null, null, location.href);
  window.onpopstate = function(event) {
    history.go(1);
  };
}

it will be not possible to go back.

Gingergingerbread answered 21/3, 2016 at 22:25 Comment(1)
currently, this disables the back button for all routes. How do I, for instance, get back button to work when I route from the dashboard to another page and click on the back button? how do I go back to the dashboard with the back button?Afreet
C
9

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.

Clock answered 6/2, 2019 at 10:47 Comment(2)
Could you format your answer better and try reorangize it?Flak
This should have been accepted as the correct answer.Bobbette
S
6

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);
    });
}
Stupefacient answered 5/1, 2019 at 14:35 Comment(1)
this works inside a useEffect Too.. thxDecade
P
1

it's not possible to disable browser buttons. my advice is to redirect user back to dashboard page if he/she is logged

Periscope answered 21/3, 2016 at 21:18 Comment(0)
K
1

Actually you can't disable back button. You can use a hack by preventing browser's "back" action. Just add to your Dashboard component compnentWillMount() lifecycle method some code that will trigger browser's "forward" action:

componentWillMount() {
   setTimeout(() => {
     window.history.forward()
   }, 0)
   window.onunload=function(){null};
}

But most probably a better solution would be some redirection based on users logged state.

Kinsey answered 21/3, 2016 at 21:30 Comment(0)
S
1

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.

Shorthand answered 18/8, 2019 at 13:54 Comment(1)
This is the best answer. history.replace(...) replaces the current view with a new view, by hitting the back button you go back to the view before that. History DocKeening
M
1

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"));
}
Milliary answered 27/4, 2020 at 6:53 Comment(6)
Currently, this disables the back button for all routes. How do I, for instance, get back button to work when I route from the dashboard to another page and click on the back button? how do I go back to the dashboard with the back button?Afreet
You can manually handle a back button or get the state of current page and store to variable when user try to go back try to check the value and proceed accordingly, otherwise if you want to override the current back button function, do not call the window.dispatchevent method instead you can write push state methodMilliary
I will really appreciate it if you could please replicate with an example to a codepen or a sandbox. Thanks.Afreet
Sure I'll provide you the sample.Milliary
Can you ask a question and tag me there so I can answer the community can also get use of itMilliary
Sure I'll do that.Afreet
L
1

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

Lasonde answered 28/12, 2020 at 13:10 Comment(1)
I found the history.listen() very helpful here -- nice solution!Curly
R
1
  • Simple and Sweet.
  • No need to mess with history stack.
  • solution even does not depend on react router.
  • It will even prevent the current component from unmounting when back button is clicked, hence it also preserves state of the app as well.
// prevent back
useEffect(() => {
    window.addEventListener('popstate', (e) => {
      window.history.go(1);
    });
  }, []);
Rouvin answered 31/10, 2022 at 6:24 Comment(2)
where do you add this code?Foreword
Inside the page where you want prevent going back in history after back button of browser is clicked.Rouvin
T
0
import React, { useEffect } from 'react';

const PreventBackNavigation = () => {
    useEffect(() => {
        const handlePopState = (e) => {
            window.history.go(1);
        };

        // Add event listener on mount
        window.addEventListener('popstate', handlePopState);

        // Clean up the event listener on unmount
        return () => {
            window.removeEventListener('popstate', handlePopState);
        };
    }, []);

    return (
        <div>
            <h1>Page with Back Navigation Disabled</h1>
        </div>
    );
};

This reloads the page when the user tries to click the back button.

Tatyanatau answered 24/5, 2024 at 5:47 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.