From 9b7882d6abb3d32564ca30824f2cec3ce4b4e3ff Mon Sep 17 00:00:00 2001 From: devvsakib Date: Sat, 27 Jul 2024 20:10:03 +0600 Subject: [PATCH] sticky table of content --- src/index.css | 1 + src/pages/Doc/single doc/index.jsx | 38 ++++++++++++++++++++++-------- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/src/index.css b/src/index.css index 49cd9cd..26d940e 100644 --- a/src/index.css +++ b/src/index.css @@ -72,6 +72,7 @@ body::-webkit-scrollbar { } html { + scroll-behavior: smooth; overflow: auto; -ms-overflow-style: none; scrollbar-width: none; diff --git a/src/pages/Doc/single doc/index.jsx b/src/pages/Doc/single doc/index.jsx index b11f59a..3f0d22c 100644 --- a/src/pages/Doc/single doc/index.jsx +++ b/src/pages/Doc/single doc/index.jsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { useParams } from 'react-router-dom'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; @@ -13,6 +13,20 @@ const DocDetail = () => { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [headings, setHeadings] = useState([]); + const tableRef = useRef(null); + + useEffect(() => { + const handleScroll = () => { + if (tableRef.current) { + const rect = tableRef.current.getBoundingClientRect(); + const isTableVisible = rect.top <= 0 && rect.bottom >= 100; + setIsSticky(isTableVisible); + } + }; + + window.addEventListener('scroll', handleScroll); + return () => window.removeEventListener('scroll', handleScroll); + }, []); useEffect(() => { const fetchContent = async () => { @@ -52,8 +66,9 @@ const DocDetail = () => { }, [content]); useEffect(() => { - if (window.location.hash) { - const id = window.location.hash.substring(1); + const hash = window.location.hash; + if (hash) { + const id = hash.substring(1); const element = document.getElementById(id); if (element) { element.scrollIntoView({ behavior: 'smooth' }); @@ -66,17 +81,20 @@ const DocDetail = () => { return ( -
+

{slug.replace(/-/g, ' ')}

-
-