That's easy. Just slap it into your root layout inside the <body>
tag.
Do not forget to import the nprogress styles in your Root Layout via import 'nprogress/progress.css';
or in your CSS via @import 'nprogress/nprogress.css';
Created
December 8, 2024 10:30
-
-
Save AmazingTurtle/8bca3866506131943caf09b9fc237395 to your computer and use it in GitHub Desktop.
NextJS App Router NProgress Compatibility Patch
This file contains 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 { useEffect } from 'react'; | |
import type { NavigateOptions } from 'next/dist/shared/lib/app-router-context.shared-runtime'; | |
import { usePathname, useRouter } from 'next/navigation'; | |
import * as NProgress from 'nprogress'; | |
export function RouterPatch() { | |
const router = useRouter(); | |
const pathname = usePathname(); | |
useEffect(() => { | |
NProgress.done(); | |
}, [pathname]); | |
useEffect(() => { | |
const origPush = router.push; | |
if (!('__is_patched' in origPush)) { | |
console.log('Patching router push'); | |
router.push = (href: string, options?: NavigateOptions) => { | |
if (href !== pathname) { | |
NProgress.start(); | |
} | |
return origPush(href, options); | |
}; | |
// @ts-expect-error __is_patched is a custom property | |
router.push.__is_patched = true; | |
} | |
const origReplace = router.replace; | |
if (!('__is_patched' in origReplace)) { | |
console.log('Patching router replace'); | |
router.replace = (href: string, options?: NavigateOptions) => { | |
if (href !== pathname) { | |
NProgress.start(); | |
} | |
return origReplace(href, options); | |
}; | |
// @ts-expect-error __is_patched is a custom property | |
router.replace.__is_patched = true; | |
} | |
return () => { | |
// unpatch when dependencies change | |
router.push = origPush; | |
router.replace = origReplace; | |
}; | |
}, [pathname, router]); | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment