From 60af6885d9761e3a2783d4d5501f6aa17c4bde13 Mon Sep 17 00:00:00 2001 From: Brent Jackson Date: Sun, 29 Jul 2018 17:16:30 -0400 Subject: [PATCH] Add hash change listeners --- src/index.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index 43ce6da..4058e09 100644 --- a/src/index.js +++ b/src/index.js @@ -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) }