React-router: Question: handling browser back button

Created on 18 Mar 2015  路  7Comments  路  Source: ReactTraining/react-router

I'm developing for mobile so getting the back button working is pretty important.
I found you can detect it with

window.onpopstate

it's passed an event with the following format
screenshot 2015-03-18 13 08 09

Any ideas how I can hook this object up to react-routers state management? I think it'd be great to just call whatever code is called when a Link component is clicked.

Most helpful comment

Do we still need to listen to window.onpopstate to handle pressing the back button in react-router? Or is there a different way to handle this now?

All 7 comments

in createClass spec using the navigation mixin

onBackButtonEvent:(e) => {
  e.preventDefault();
 this.goBack();
}

componentDidMount: () => {
  window.onpopstate = this.onBackButtonEvent;
}

awesome. goBack() didn't work for some reason so I went with transitionTo()
here's the code

var ChatRoom = React.createClass({
  mixins: [State, Navigation],

  onBackButtonEvent: function (e) {
    debug('handling back button press')
    e.preventDefault()
    this.transitionTo('chatrooms')
  },

  componentDidMount: function() {
    window.onpopstate = this.onBackButtonEvent
  },

  render: function() {
    return (
    // jsx
    )
  }
})

module.exports = ChatRoom

In this document says, the popstate event is not cancellable.

Specification: HTML5
Interface: PopStateEvent
Bubbles: Yes
Cancelable: No
Target: defaultView
Default Action: None

window.onpopstate gets called when going forward as well

Do we still need to listen to window.onpopstate to handle pressing the back button in react-router? Or is there a different way to handle this now?

 componentDidUpdate(){
  window.onpopstate  = (e) => {
        //your code...
    }
  }

@probablycorey unless otherwise noted, it's the same

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ArthurRougier picture ArthurRougier  路  3Comments

andrewpillar picture andrewpillar  路  3Comments

misterwilliam picture misterwilliam  路  3Comments

yormi picture yormi  路  3Comments

Waquo picture Waquo  路  3Comments