Loading Screen on next js page transition

前端 未结 3 2028
礼貌的吻别
礼貌的吻别 2021-02-04 13:53

I am trying to implement a loading screen when changing routes in my Nextjs app ,for example /home -> /about.

My current implementation is as follows. I am setting the

3条回答
  •  灰色年华
    2021-02-04 14:25

    Using the new hook api, this is how I would do it..

    function Loading() {
        const router = useRouter();
    
        const [loading, setLoading] = useState(false);
    
        useEffect(() => {
            const handleStart = (url) => (url !== router.asPath) && setLoading(true);
            const handleComplete = (url) => (url === router.asPath) && setLoading(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 loading && (
    Loading....{/*I have an animation here*/}
    ); }

    Now is going to show up whenever the route will change... I animate this using react-spring, but you can use any library you prefer to do this.

    You can even take a step further and modify when the component shows up by modifying the handleStart and handleComplete methods that gets a url.

提交回复
热议问题