Last active
November 6, 2022 11:34
-
-
Save nanderLP/605f275e0f1cb68aec9c8689e0132e2f to your computer and use it in GitHub Desktop.
Router Navigation Indicator
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
import { useTheme } from "@chakra-ui/react"; | |
import { AnimatePresence, motion } from "framer-motion"; | |
import { useRouter } from "next/router"; | |
import { FC, useEffect, useState } from "react"; | |
/** | |
* Little component for Next.js that implements a UI indicator for route navigation. Made with Framer Motion | |
* Should be absolute positioned to the top of the page | |
* NOTE: Next.js 13 is not supported, as it has a different router implementation | |
*/ | |
export const RouteProgressBar: FC = () => { | |
const router = useRouter(); | |
// You can use basically anything as long as you define a color for the progress bar | |
const theme = useTheme(); | |
const [routeChanging, setRouteChanging] = useState(false); | |
useEffect(() => { | |
const handleStart = () => setRouteChanging(true); | |
const handleComplete = () => setRouteChanging(false); | |
router.events.on("routeChangeStart", handleStart); | |
router.events.on("routeChangeComplete", handleComplete); | |
router.events.on("routeChangeError", handleComplete); | |
return () => { | |
router.events.off("routeChangeStart", handleStart); | |
router.events.off("routeChangeComplete", handleComplete); | |
router.events.off("routeChangeError", handleComplete); | |
}; | |
}); | |
return ( | |
<AnimatePresence> | |
{routeChanging && ( | |
<motion.div | |
initial={{ width: "0%" }} | |
animate={{ width: "25%" }} | |
exit={{ opacity: 0, width: "100%" }} | |
style={{ | |
position: "fixed", | |
top: "0", | |
height: "4px", | |
backgroundColor: theme.colors.primary.base, | |
}} | |
></motion.div> | |
)} | |
</AnimatePresence> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment