/
index.js
64 lines (56 loc) · 1.76 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { useState, useEffect, useCallback } from 'react'
import ReactDOM from 'react-dom/client'
const container = document.getElementById('wrap')
const root = ReactDOM.createRoot(container)
const App = () => {
const [historyIndex, setHistoryIndex] = useState(0)
const [direction, setDirection] = useState('None')
useEffect(() => {
const index = window.history.state?.index
if(index) {
setHistoryIndex(index)
} else {
window.history.replaceState({ index: 0 }, '')
}
}, [])
useEffect(() => {
window.history.pushState = (state, ...arg) => {
const index = historyIndex + 1
setHistoryIndex(index)
return History.prototype.pushState.apply(
window.history,
[{ ...state, index }, ...arg]
)
}
window.history.replaceState = (state, ...arg) => {
return History.prototype.replaceState.apply(
window.history,
[{ ...state, index: historyIndex }, ...arg]
)
}
window.addEventListener('popstate', onPopstate)
return () => {
window.removeEventListener('popstate', onPopstate)
}
}, [historyIndex])
const onPopstate = useCallback(() => {
const { state } = window.history
if (!state) window.history.replaceState({ index: historyIndex + 1 }, '')
const index = state ? state.index : historyIndex + 1
setHistoryIndex(index)
setDirection(index > historyIndex ? 'forward' : 'back')
}, [historyIndex])
return (
<div>
<h1>Direction: {direction}</h1>
<ul>
<li onClick={() => window.history.pushState({}, '', '#1')}>#1</li>
<li onClick={() => window.history.pushState({}, '', '#2')}>#2</li>
<li onClick={() => window.history.pushState({}, '', '#3')}>#3</li>
</ul>
</div>
)
}
root.render(
<App />
)