Skip to content

Commit 47d2dfd

Browse files
Update examples/active-class-name (#62506)
### Description The current implementation of the activeClassName example doesn't support the `UrlObject` type for the "href" Link prop. For example ``` <ActiveLink activeClassName="active" className="nav-link" href={{ pathname: "/[slug]", query: { slug: "dynamic-route", }, }} > Dynamic Route </ActiveLink> ``` won't work. ### Suggestion We can use the `resolveHref` function to handle all cases. Co-authored-by: Sam Ko <[email protected]>
1 parent fb14590 commit 47d2dfd

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed

examples/active-class-name/components/ActiveLink.tsx

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,26 @@
11
import { useRouter } from "next/router";
22
import Link, { LinkProps } from "next/link";
3-
import React, { PropsWithChildren, useState, useEffect } from "react";
3+
import React, { PropsWithChildren, useEffect, useState } from "react";
4+
import { NextRouter } from "next/src/shared/lib/router/router";
5+
import { resolveHref } from "next/dist/client/resolve-href";
6+
7+
const getLinkUrl = (params: {
8+
router: NextRouter;
9+
href: LinkProps["href"];
10+
as: LinkProps["as"];
11+
}): string => {
12+
// Dynamic route will be matched via props.as
13+
// Static route will be matched via props.href
14+
if (params.as) return resolveHref(params.router, params.as);
15+
16+
const [resolvedHref, resolvedAs] = resolveHref(
17+
params.router,
18+
params.href,
19+
true,
20+
);
21+
22+
return resolvedAs || resolvedHref;
23+
};
424

525
type ActiveLinkProps = LinkProps & {
626
className?: string;
@@ -13,21 +33,22 @@ const ActiveLink = ({
1333
className,
1434
...props
1535
}: PropsWithChildren<ActiveLinkProps>) => {
16-
const { asPath, isReady } = useRouter();
36+
const router = useRouter();
1737
const [computedClassName, setComputedClassName] = useState(className);
1838

1939
useEffect(() => {
2040
// Check if the router fields are updated client-side
21-
if (isReady) {
22-
// Dynamic route will be matched via props.as
23-
// Static route will be matched via props.href
24-
const linkPathname = new URL(
25-
(props.as || props.href) as string,
26-
location.href,
27-
).pathname;
41+
if (router.isReady) {
42+
const linkUrl = getLinkUrl({
43+
router,
44+
href: props.href,
45+
as: props.as,
46+
});
47+
48+
const linkPathname = new URL(linkUrl, location.href).pathname;
2849

2950
// Using URL().pathname to get rid of query and hash
30-
const activePathname = new URL(asPath, location.href).pathname;
51+
const activePathname = new URL(router.asPath, location.href).pathname;
3152

3253
const newClassName =
3354
linkPathname === activePathname
@@ -39,8 +60,7 @@ const ActiveLink = ({
3960
}
4061
}
4162
}, [
42-
asPath,
43-
isReady,
63+
router,
4464
props.as,
4565
props.href,
4666
activeClassName,

0 commit comments

Comments
 (0)