Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 3b3bb8a

Browse files
author
Je
committed
feat: add NavLink Component
1 parent d0761a9 commit 3b3bb8a

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

link.ts

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ interface LinkProps {
1414

1515
const fetchedPageModules = new Set<string>()
1616

17-
export default function Link({
17+
export function Link({
1818
to,
1919
replace = false,
2020
prefetch: prefetchImmediately = false,
@@ -100,3 +100,43 @@ export default function Link({
100100
children
101101
)
102102
}
103+
104+
interface NavLinkProps extends LinkProps {
105+
activeClassName?: string
106+
activeStyle?: CSSProperties
107+
}
108+
109+
export function NavLink({
110+
activeClassName = 'active',
111+
activeStyle,
112+
to,
113+
...rest
114+
}: PropsWithChildren<NavLinkProps>) {
115+
const { pathname: currentPathname } = useRouter()
116+
const pathname = useMemo(() => {
117+
if (util.isHttpUrl(to)) {
118+
return to
119+
}
120+
let [pathname] = util.splitBy(to, '?')
121+
if (pathname.startsWith('/')) {
122+
pathname = util.cleanPath(pathname)
123+
} else {
124+
pathname = util.cleanPath(currentPathname + '/' + pathname)
125+
}
126+
return pathname
127+
}, [currentPathname, to])
128+
129+
if (currentPathname === pathname) {
130+
return React.createElement(
131+
Link,
132+
{
133+
...rest,
134+
to,
135+
className: [rest.className?.trim(), activeClassName.trim()].filter(Boolean).join(' '),
136+
style: Object.assign({}, rest.style, activeStyle)
137+
}
138+
)
139+
}
140+
141+
return React.createElement(Link, { ...rest, to })
142+
}

mod.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@ export { redirect } from './aleph.ts'
22
export * from './context.ts'
33
export { default as Head, SEO, Viewport } from './head.ts'
44
export * from './hooks.ts'
5-
export { default as Link } from './link.ts'
5+
export { Link, NavLink } from './link.ts'
66
export const Import = (_: { from: string }) => null

0 commit comments

Comments
 (0)