Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: handling browser back button #967

Closed
morenoh149 opened this issue Mar 18, 2015 · 7 comments
Closed

Question: handling browser back button #967

morenoh149 opened this issue Mar 18, 2015 · 7 comments

Comments

@morenoh149
Copy link
Contributor

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.

@BerkeleyTrue
Copy link

in createClass spec using the navigation mixin

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

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

@morenoh149
Copy link
Contributor Author

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

@codemilli
Copy link

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

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

@ccorcos
Copy link

ccorcos commented Jul 18, 2017

window.onpopstate gets called when going forward as well

@probablycorey
Copy link

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?

@viru9
Copy link

viru9 commented Jul 25, 2018

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

@morenoh149
Copy link
Contributor Author

@probablycorey unless otherwise noted, it's the same

@lock lock bot locked as resolved and limited conversation to collaborators Sep 23, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants