Smooth Scroll
A client-side hook that enables smooth scrolling behavior for anchor links with an automatic offset adjustment.
src/hooks/smooth-scroll.tsx
Usage
import SmoothScroll from '@/hooks/smooth-scroll'
export default function Layout() {
return (
<>
<SmoothScroll />
{}
</>
)
}
Features
- Automatically attaches smooth scroll behavior to all anchor links (
a[href^="#"])
- Applies a 40px offset from the top when scrolling to anchors
- Updates the URL hash in browser history
- Dynamically observes DOM changes to attach listeners to new links
- Opt-out available by adding
no-anchor-scroll class to specific links
- Reattaches listeners on route changes via Next.js pathname monitoring
How it Works
- Detects clicks on anchor links starting with
#
- Prevents default browser jump behavior
- Smoothly scrolls to the target element with offset
- Updates the URL without page reload
- Uses MutationObserver to handle dynamically added links
Excluding Links
To exclude specific links from smooth scrolling, add the no-anchor-scroll class:
<a
href="#section"
className="no-anchor-scroll"
>
Jump without smooth scroll
</a>
Implementation
The component is used in src/app/layout.tsx to enable smooth scrolling throughout the application.