Skip to content

Commit 891f825

Browse files
committed
Add isActive function to NavLink
1 parent feb3471 commit 891f825

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/index.js

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -72,17 +72,26 @@ function hashLinkScroll(timeout) {
7272

7373
export function genericHashLink(As) {
7474
return React.forwardRef((props, ref) => {
75+
let linkHash = '';
76+
if (typeof props.to === 'string' && props.to.includes('#')) {
77+
linkHash = `#${props.to.split('#').slice(1).join('#')}`;
78+
} else if (
79+
typeof props.to === 'object' &&
80+
typeof props.to.hash === 'string'
81+
) {
82+
linkHash = props.to.hash;
83+
}
84+
85+
const passDownProps = {};
86+
if (As === NavLink) {
87+
passDownProps.isActive = (match, location) =>
88+
match && match.isExact && location.hash === linkHash;
89+
}
90+
7591
function handleClick(e) {
7692
reset();
93+
hashFragment = linkHash;
7794
if (props.onClick) props.onClick(e);
78-
if (typeof props.to === 'string' && props.to.includes('#')) {
79-
hashFragment = `#${props.to.split('#').slice(1).join('#')}`;
80-
} else if (
81-
typeof props.to === 'object' &&
82-
typeof props.to.hash === 'string'
83-
) {
84-
hashFragment = props.to.hash;
85-
}
8695
if (hashFragment !== '') {
8796
scrollFunction =
8897
props.scroll ||
@@ -95,7 +104,7 @@ export function genericHashLink(As) {
95104
}
96105
const { scroll, smooth, timeout, ...filteredProps } = props;
97106
return (
98-
<As {...filteredProps} onClick={handleClick} ref={ref}>
107+
<As {...passDownProps} {...filteredProps} onClick={handleClick} ref={ref}>
99108
{props.children}
100109
</As>
101110
);

0 commit comments

Comments
 (0)