Skip to content

Commit 33ed5f1

Browse files
committed
Reset on every click regardless of if hash is present
1 parent 749d057 commit 33ed5f1

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

src/index.js

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@ import { Link } from 'react-router-dom';
33

44
let hashFragment = '';
55
let observer = null;
6-
let asyncTimer = null;
6+
let asyncTimerId = null;
77

88
function reset() {
99
hashFragment = '';
1010
if (observer !== null) observer.disconnect();
11-
if (asyncTimer !== null) {
12-
window.clearTimeout(asyncTimer);
13-
asyncTimer = null;
11+
if (asyncTimerId !== null) {
12+
window.clearTimeout(asyncTimerId);
13+
asyncTimerId = null;
1414
}
1515
}
1616

@@ -24,19 +24,16 @@ function getElAndScroll() {
2424
return false;
2525
}
2626

27-
function setupMutationObserver() {
28-
observer = new MutationObserver(getElAndScroll);
29-
}
30-
3127
function hashLinkScroll() {
3228
// Push onto callback queue so it runs after the DOM is updated
33-
setTimeout(() => {
29+
window.setTimeout(() => {
3430
if (getElAndScroll() === false) {
35-
if (observer === null) setupMutationObserver();
31+
if (observer === null) {
32+
observer = new MutationObserver(getElAndScroll);
33+
}
3634
observer.observe(document, { attributes: true, childList: true, subtree: true });
37-
if (asyncTimer !== null) window.clearTimeout(asyncTimer);
3835
// if the element doesn't show up in 10 seconds, stop checking
39-
asyncTimer = window.setTimeout(() => {
36+
asyncTimerId = window.setTimeout(() => {
4037
reset();
4138
}, 10000);
4239
}
@@ -46,16 +43,13 @@ function hashLinkScroll() {
4643
export function HashLink(props) {
4744
function handleClick(e) {
4845
if (props.onClick) props.onClick(e);
49-
let hash = '';
46+
reset();
5047
if (typeof props.to === 'string') {
51-
hash = props.to.split('#').slice(1).join('#');
48+
hashFragment = props.to.split('#').slice(1).join('#');
5249
} else if (typeof props.to === 'object' && typeof props.to.hash === 'string') {
53-
hash = props.to.hash.replace('#', '');
54-
}
55-
if (hash !== '') {
56-
hashFragment = hash;
57-
hashLinkScroll();
50+
hashFragment = props.to.hash.replace('#', '');
5851
}
52+
if (hashFragment !== '') hashLinkScroll();
5953
}
6054
return <Link {...props} onClick={handleClick}>{props.children}</Link>;
6155
}

0 commit comments

Comments
 (0)