1
1
mirror of https://github.com/jxnblk/mdx-deck.git synced 2024-09-20 19:37:27 +03:00

Add hash change listeners

This commit is contained in:
Brent Jackson 2018-07-29 17:16:30 -04:00
parent 242cd9e906
commit 60af6885d9

View File

@ -176,19 +176,34 @@ export class SlideDeck extends React.Component {
}
}
componentDidMount () {
document.body.addEventListener('keydown', this.handleKeyDown)
handleHashChange = e => {
this.isHashChange = true
this.hashToState()
}
hashToState = () => {
const { hash } = window.location
const index = parseInt(hash.replace(/^#/, ''), 10)
if (isNaN(index)) return
this.setState({ index })
}
componentDidMount () {
document.body.addEventListener('keydown', this.handleKeyDown)
window.addEventListener('hashchange', this.handleHashChange)
this.hashToState()
}
componentWillUnmount () {
document.body.removeEventListener('keydown', this.handleKeyDown)
window.removeEventListener('hashchange', this.handleHashChange)
}
componentDidUpdate () {
if (this.isHashChange) {
this.isHashChange = false
return
}
const { index } = this.state
history.pushState(null, null, '/#' + index)
}