forked from rocicorp/zero-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActiveHashLink.tsx
More file actions
44 lines (40 loc) · 963 Bytes
/
ActiveHashLink.tsx
File metadata and controls
44 lines (40 loc) · 963 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
'use client';
import clsx from 'clsx';
import Link from 'next/link';
import {useParams, usePathname} from 'next/navigation';
import {useEffect, useMemo, useRef} from 'react';
import useHash from '../hooks/useHash';
interface ActiveHashLinkProps {
href: string;
children: React.ReactNode;
className?: string;
activeClassName?: string;
}
export const ActiveHashLink: React.FC<ActiveHashLinkProps> = ({
href,
children,
className = '',
activeClassName = '',
}) => {
const ref = useRef<HTMLAnchorElement>(null);
const linkHash = useHash();
const isActive = linkHash === href;
useEffect(() => {
if (isActive && ref.current) {
ref.current.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start',
});
}
}, [isActive]);
return (
<Link
ref={ref}
href={href}
className={clsx(className, {[activeClassName]: isActive})}
>
{children}
</Link>
);
};