Intercept/handle browser's back button in React-router?

Intercept/handle browser's back button in React-router?

how to handle browser back button in react js
react-router-dom browser back button
disable browser back button in react js
window.onpopstate react
react-router-dom back button
react-router browser history
angular-http interceptor error handling
react router 4 prevent back

I'm using Material-ui's Tabs, which are controlled and I'm using them for (React-router) Links like this:

    <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/>
    <Tab value={1} label="users" containerElement={<Link to="/dashboard/users"/>} />
  <Tab value={2} label="data" containerElement={<Link to="/dashboard/data"/>} />

If I'm currenlty visting dashboard/data and I click browser's back button I go (for example) to dashboard/users but the highlighted Tab still stays on dashboard/data (value=2)

I can change by setting state, but I don't know how to handle the event when the browser's back button is pressed?

I've found this:

window.onpopstate = this.onBackButtonEvent;

but this is called each time state is changed (not only on back button event)

This is a bit old question and you've probably already got your answer, but for people like me who needed this, I'm leaving this answer.

Using react-router made the job simple as such:

import { browserHistory } from 'react-router';

componentDidMount() {


    this.backListener = browserHistory.listen(location => {
      if (location.action === "POP") {
        // Do your stuff

componentWillUnmount() {
    // Unbind listener

Intercept HTTP requests, Angular 6 & 7 HTTP Client Interceptor with Error handling. You also need to And open http://localhost:4200 in your browser. Adding material  Faster Browsing with Built-in Adblock, Webcam Guard, Anti-Track and Other Features. Browser That Brings All Privacy and Security Tools Together in One Place.

here is how I ended up doing it:

componentDidMount() {
    this._isMounted = true;
    window.onpopstate = ()=> {
      if(this._isMounted) {
        const { hash } = location;
        if(hash.indexOf('home')>-1 && this.state.value!==0)
          this.setState({value: 0})
        if(hash.indexOf('users')>-1 && this.state.value!==1)
          this.setState({value: 1})
        if(hash.indexOf('data')>-1 && this.state.value!==2)
          this.setState({value: 2})

thanks everybody for helping lol

Creating Angular Interceptor, [SOLVED] Intercept/handle browser's back button in React-router? | JavaScript Knowledge Base. If you use BrowserRouter from react-router (not available in react-router v4 though), as mentioned above, you can use the action 'POP' to intercept the browser back button. However, if you use HashRouter to push the routes, above solution will not work.

Version 3.x of the React Router API has a set of utilities you can use to expose a "Back" button event before the event registers with the browser's history. You must first wrap your component in the withRouter() higher-order component. You can then use the setRouteLeaveHook() function, which accepts any route object with a valid path property and a callback function.

import {Component} from 'react';
import {withRouter} from 'react-router';

class Foo extends Component {
  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);

  routerWillLeave(nextState) { // return false to block navigation, true to allow
    if (nextState.action === 'POP') {
      // handle "Back" button clicks here

export default withRouter(Foo);

[SOLVED] Intercept/handle browser's back button in React-router , There are many ways to use an interceptor, and I'm sure most of us have only a way to intercept HTTP requests and responses to transform or handle them  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {} In this example you will set token, Content-Type, Accept type in API request. const token: string = localStorage.getItem('token');

I used withrouter hoc in order to get history prop and just write a componentDidMount() method:

componentDidMount() {
    if (this.props.history.action === "POP") {
        // custom back button implementation

Top 10 ways to use Interceptors in Angular, Handling http requests in Angular it's very easy and well done. an http request to an API and visualize the response of this action inside the browser console. Hi , How can i intercept the back button of the web browser ,so tht whenn iot is clicked by the user they are redirected to the previous page and also when they click the forward button they are di

Hooks sample

    const { history } = useRouter();

useEffect(() => {
    return () => {
        if (history.action === "POP") // && history.location.pathname === "any specific path") {
            history.replace(history.location.pathname, /* the new state */);
}, [history])

I don't use history.listen because it doesn't affect the state

const disposeListener = history.listen(navData => {
        if (navData.pathname === "/props") {
            navData.state = /* the new state */;

Intercept HTTP Requests in Angular - Denis Cangemi, We will compare several solutions for error handling in Angular apps. That's because the code is now running on the client browser. It provides a way to intercept http requests and responses to transform or handle them  Learn everything about the new Http client introduced in Angular 4.3 and now default in Angular 5 in my latest video course on “Learn HTTP in Angular”.. In the following video lesson I implement an HTTP interceptor which intercepts the request, adding some headers, the response as well as potential HTTP errors.

Error Handling with Angular 6 - Tips and Best Practices, Interceptor enables you to sync cookies from your browser to Postman and capture network requests directly from Chrome, saving them to your history or Postman  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {} In this example I am going to set token, Content-Type, Accept type in API request. const token: string = localStorage.getItem('token');

Interceptor, handle(transformedReq) . An interceptor may transform the response event stream as well, by applying additional RxJS operators on the stream returned by next. And apart from this above option, the best way you can handle such cases is by creating sessions with no activity timeout of may be 25-30 mins. Convert all your cookies that need to be destroyed into sessions with timeout. Alternately, you can set cookie expiry but then the cookie stays in the browser until next login.

Interceptor, In modern browsers AJAX functionality is implemented using either An interceptor contains the logic of handling a request but to be used with  Hi Shiv. This seems to be working fine for most cases except for ALT+F4 when there is no other tab i.e. open the page in browser and press Alt + F4. This closes browser without message. Ctrl + F4 works in the same situation.. Any Idea? – Milind Thakkar Aug 1 '16 at 18:21. Also, it is firing in case you click browser back or forward as mouse