Skip to content

Commit 6e994ce

Browse files
committed
feat: added auto scroll toc
1 parent 6bdaec0 commit 6e994ce

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

apps/website/components/custom/toc/index.tsx

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { usePathname } from 'next/navigation';
2-
import React, { useEffect, useState } from 'react';
2+
import React, { useEffect, useRef, useState } from 'react';
33

44
interface HeadingItem {
55
id: string;
@@ -39,6 +39,18 @@ export const TOC: React.FC = () => {
3939

4040
const pathname = usePathname();
4141

42+
const tocRefs = useRef<Record<string, HTMLAnchorElement | null>>({});
43+
useEffect(() => {
44+
const activeEl = tocRefs.current[activeId];
45+
if (activeEl) {
46+
activeEl.scrollIntoView({
47+
block: 'nearest',
48+
inline: 'nearest',
49+
behavior: 'smooth',
50+
});
51+
}
52+
}, [activeId]);
53+
4254
useEffect(() => {
4355
// Grab h1–h5
4456
const scrollContainer = document.getElementById('layout-content');
@@ -146,6 +158,9 @@ export const TOC: React.FC = () => {
146158
return (
147159
<li key={item.id} className="relative">
148160
<a
161+
ref={(el) => {
162+
tocRefs.current[item.id] = el;
163+
}}
149164
href={`#${item.id}`}
150165
onClick={handleClick(item.id)}
151166
className={`

0 commit comments

Comments
 (0)