Created
July 30, 2023 18:42
-
-
Save saitergun/8d9baa1244b264a8932ea51b3f4571c8 to your computer and use it in GitHub Desktop.
NProgress provider component for Next.js app routing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client' | |
import { usePathname } from 'next/navigation' | |
import { useEffect, useRef } from 'react' | |
import NProgress from 'nprogress' | |
import 'nprogress/nprogress.css' | |
type Props = { | |
children: React.ReactNode | |
} | |
NProgress.configure({ | |
showSpinner: false, | |
trickle: true, | |
trickleSpeed: 200, | |
minimum: 0.08, | |
speed: 200, | |
easing: 'ease', | |
}) | |
export default function NProgressProvider({ children }: Props) { | |
const timeOutRef = useRef<NodeJS.Timeout>() | |
const pathname = usePathname() | |
useEffect(() => { | |
if (timeOutRef.current) { | |
clearTimeout(timeOutRef.current) | |
NProgress.done() | |
} | |
const handleClickWindow = (e: MouseEvent) => { | |
const el = e.target as HTMLElement | |
if (el.nodeName === 'A') { | |
const href = el.getAttribute('href') as string | |
let nextUrl = new URL(href, window.location.origin) | |
if (pathname !== nextUrl.pathname) { | |
timeOutRef.current = setTimeout(() => { | |
NProgress.start() | |
}, 300) | |
} | |
} | |
} | |
window.addEventListener('click', handleClickWindow) | |
return () => { | |
window.removeEventListener('click', handleClickWindow) | |
} | |
}, [pathname]) | |
return <>{children}</> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment