Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
- Ajayff4
- akx
- awreese
- bhbs
- brockross
Expand Down
57 changes: 41 additions & 16 deletions packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
useRoutes,
useOutletContext
} from "react-router";
import type { To } from "react-router";
import type { To, Path } from "react-router";

function warning(cond: boolean, message: string): void {
if (!cond) {
Expand Down Expand Up @@ -311,21 +311,7 @@ export const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(
},
ref
) {
let location = useLocation();
let path = useResolvedPath(to);

let locationPathname = location.pathname;
let toPathname = path.pathname;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
toPathname = toPathname.toLowerCase();
}

let isActive =
locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(toPathname.length) === "/");
let isActive = useIsPathActive(to, caseSensitive, end);

let ariaCurrent = isActive ? ariaCurrentProp : undefined;

Expand Down Expand Up @@ -411,6 +397,20 @@ export function useLinkClickHandler<E extends Element = HTMLAnchorElement>(
);
}

/**
* Returns true if the given location seems currently active.
* `caseSensitive` and `end` work the same as with `<NavLink>`.
*/
export function useIsPathActive(
to: To,
caseSensitive: boolean = false,
end: boolean = false
): boolean {
let location = useLocation();
let path = useResolvedPath(to);
return isPathActive(location, path, caseSensitive, end);
}

/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
Expand Down Expand Up @@ -504,3 +504,28 @@ export function createSearchParams(
}, [] as ParamKeyValuePair[])
);
}

/**
* Given a location and a path, returns true if the path is active in the location.
* `caseSensitive` and `end` work the same as with `<NavLink>`.
*/
export function isPathActive(
location: Path,
path: Path,
caseSensitive: boolean = false,
end: boolean = false
) {
let locationPathname = location.pathname;
let toPathname = path.pathname;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
toPathname = toPathname.toLowerCase();
}

return (
locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(toPathname.length) === "/")
);
}