Skip to content

Commit b616e6f

Browse files
committed
Only call hashLinkScroll when hash is present
1 parent c83e0ec commit b616e6f

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/index.js

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,33 @@
11
import React, { PropTypes } from 'react';
22
import { Link } from 'react-router-dom';
33

4-
function hashLinkScroll() {
4+
function hashLinkScroll(hashFragment) {
55
// Push onto callback queue so it runs after the DOM is updated
66
setTimeout(() => {
7-
const { hash } = window.location;
8-
if (hash !== '') {
9-
const id = hash.replace('#', '');
10-
const element = document.getElementById(id);
11-
if (element) element.scrollIntoView();
12-
}
7+
const element = document.getElementById(hashFragment);
8+
if (element) element.scrollIntoView();
139
}, 0);
1410
}
1511

1612
export function HashLink(props) {
1713
function handleClick(e) {
1814
if (props.onClick) props.onClick(e);
19-
hashLinkScroll();
15+
let hashFragment = '';
16+
if (typeof props.to === 'string') {
17+
hashFragment = props.to.split('#').slice(1).join('#');
18+
} else if (typeof props.to === 'object' && props.to.hash) {
19+
hashFragment = props.to.hash.replace('#', '');
20+
}
21+
if (hashFragment) hashLinkScroll(hashFragment);
2022
}
2123
return <Link {...props} onClick={handleClick}>{props.children}</Link>;
2224
}
2325

2426
HashLink.PropTypes = {
2527
onClick: PropTypes.func,
2628
children: PropTypes.node,
29+
to: PropTypes.oneOfType([
30+
PropTypes.string,
31+
PropTypes.object,
32+
]),
2733
};

0 commit comments

Comments
 (0)