Skip to content

Instantly share code, notes, and snippets.

@nanderLP
Last active November 6, 2022 11:34
Show Gist options
  • Save nanderLP/605f275e0f1cb68aec9c8689e0132e2f to your computer and use it in GitHub Desktop.
Save nanderLP/605f275e0f1cb68aec9c8689e0132e2f to your computer and use it in GitHub Desktop.
Router Navigation Indicator
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