Skip to content

Commit 42191df

Browse files
authored
Forward refs properly
1 parent 0682234 commit 42191df

File tree

1 file changed

+34
-36
lines changed

1 file changed

+34
-36
lines changed

src/index.js

Lines changed: 34 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -46,46 +46,44 @@ function hashLinkScroll() {
4646
}, 0);
4747
}
4848

49-
export function genericHashLink(props, As) {
50-
function handleClick(e) {
51-
reset();
52-
if (props.onClick) props.onClick(e);
53-
if (typeof props.to === 'string') {
54-
hashFragment = props.to
55-
.split('#')
56-
.slice(1)
57-
.join('#');
58-
} else if (
59-
typeof props.to === 'object' &&
60-
typeof props.to.hash === 'string'
61-
) {
62-
hashFragment = props.to.hash.replace('#', '');
63-
}
64-
if (hashFragment !== '') {
65-
scrollFunction =
66-
props.scroll ||
67-
(el =>
68-
props.smooth
69-
? el.scrollIntoView({ behavior: "smooth" })
70-
: el.scrollIntoView());
71-
hashLinkScroll();
49+
export function genericHashLink(As) {
50+
return React.forwardRef((props, ref) => {
51+
function handleClick(e) {
52+
reset();
53+
if (props.onClick) props.onClick(e);
54+
if (typeof props.to === 'string') {
55+
hashFragment = props.to
56+
.split('#')
57+
.slice(1)
58+
.join('#');
59+
} else if (
60+
typeof props.to === 'object' &&
61+
typeof props.to.hash === 'string'
62+
) {
63+
hashFragment = props.to.hash.replace('#', '');
64+
}
65+
if (hashFragment !== '') {
66+
scrollFunction =
67+
props.scroll ||
68+
(el =>
69+
props.smooth
70+
? el.scrollIntoView({ behavior: "smooth" })
71+
: el.scrollIntoView());
72+
hashLinkScroll();
73+
}
7274
}
73-
}
74-
const { scroll, smooth, ...filteredProps } = props;
75-
return (
76-
<As {...filteredProps} onClick={handleClick}>
77-
{props.children}
78-
</As>
79-
);
75+
const { scroll, smooth, ...filteredProps } = props;
76+
return (
77+
<As {...filteredProps} onClick={handleClick} ref={ref}>
78+
{props.children}
79+
</As>
80+
);
81+
});
8082
}
8183

82-
export function HashLink(props) {
83-
return genericHashLink(props, Link);
84-
}
84+
export const HashLink = genericHashLink(Link);
8585

86-
export function NavHashLink(props) {
87-
return genericHashLink(props, NavLink);
88-
}
86+
export const NavHashLink = genericHashLink(NavLink);
8987

9088
const propTypes = {
9189
onClick: PropTypes.func,

0 commit comments

Comments
 (0)