Jump to content
Search Community

nina-alin

Members
  • Posts

    1
  • Joined

  • Last visited

Everything posted by nina-alin

  1. I managed to create a page transition using the Next 13 App router. However, I'm quite certain that this isn't the optimal approach. I encountered an issue where, due to the heftiness of my pages, the animation would unexpectedly occur before the page had completely loaded. Since the useRouter router in Next 13 does not return a Promise, I couldn't wait for the page to load before triggering my animation. Because of this, I resorted to using a good old setTimeout. I also attempted to use the useTransition hook from React, but I encountered some strange behavior. Here's a minimal code example of what I did. I'm open to any suggestions for improvement. I'm sharing this because it might be helpful to others. const RootLayout = async ({ children, }: { children: React.ReactNode; }) => { return ( <html> <body> <TransitionProvider> <Navbar /> <TransitionHandler> {children} </TransitionHandler> </TransitionProvider> </body> </html> ); }; export const TransitionContext = createContext<{ url: string; setUrl: Dispatch<SetStateAction<string>>; }>({ url: "", setUrl: () => {}, }); const TransitionProvider = ({ children }: { children: ReactNode }) => { const pathname = usePathname(); const [url, setUrl] = useState<string>(pathname); return ( <TransitionContext.Provider value={{ url, setUrl }}> {children} </TransitionContext.Provider> ); }; export default TransitionProvider; export default function TransitionHandler({ children, }: { children: ReactNode; }) { const elementReference = useRef(null); const firstLoadReference = useRef(true); const router = useRouter(); const { url, setUrl } = useContext(TransitionContext); useEffect(() => { if (!firstLoadReference.current) { const element = elementReference.current; const onPageExit = (element: null) => { router.prefetch(url); // your page exit animation }; const onPageEnter = (element: null, url: string) => { router.push(url); // TODO: find a better solution setTimeout(() => { // your page enter animation }, 500); }; onPageExit(element); } firstLoadReference.current = false; }, [router, url, firstLoadReference]); return <div ref={elementReference}>{children}</div>; } const Navbar = () => { const {url, setUrl} = useContext(TransitionContext); return ( <button onClick={() => setUrl("/my-url")} click </button> )}
×
×
  • Create New...