From a00cbe3610b5f9d23a3311bc195079b87faef798 Mon Sep 17 00:00:00 2001 From: Nick Randall Date: Wed, 16 Mar 2022 08:26:07 -0700 Subject: [PATCH 1/2] feat(usePathIsActive): expose hook --- packages/react-router-dom/index.tsx | 49 +++++++++++++++++++---------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/packages/react-router-dom/index.tsx b/packages/react-router-dom/index.tsx index 00d8639788..75fe1962c1 100644 --- a/packages/react-router-dom/index.tsx +++ b/packages/react-router-dom/index.tsx @@ -288,6 +288,38 @@ if (__DEV__) { Link.displayName = "Link"; } +export interface IsActiveProps { + to: To; + caseSensitive?: boolean; + end?: boolean; +} + +/** + * A hook that returns true if the given path is "active" or not. + */ +export const usePathIsActive = ({ + to, + caseSensitive, + end, +}: IsActiveProps): boolean => { + let location = useLocation(); + let path = useResolvedPath(to); + + 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) === "/") + ); +}; + export interface NavLinkProps extends Omit { children: @@ -318,22 +350,7 @@ export const NavLink = React.forwardRef( }, 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 = usePathIsActive({ to, caseSensitive, end }); let ariaCurrent = isActive ? ariaCurrentProp : undefined; let className: string | undefined; From fa90aecc2c55d641570bd706d41eb0b98df57de6 Mon Sep 17 00:00:00 2001 From: Nick Randall Date: Wed, 16 Mar 2022 10:13:14 -0700 Subject: [PATCH 2/2] adding self to contributors.yml --- contributors.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/contributors.yml b/contributors.yml index 982ef838a5..084ac61831 100644 --- a/contributors.yml +++ b/contributors.yml @@ -34,6 +34,7 @@ - mcansh - mfijas - noisypigeon +- nicksrandall - paulsmithkc - petersendidit - RobHannay