본문으로 바로가기

github.com/vercel/next.js/tree/canary/examples/with-loading

nextjs.org/docs/api-reference/next/router#routerevents

 

next/router | Next.js

Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook.

nextjs.org

 

일반적으로 아래와 같이 useRouter를 이용해 앱 내의 이동을 구현했습니다.

import { useRouter } from 'next/router'

function Component() {
  const router = useRouter()
  ... 중략
}

export default Component

 

그러나.. Sometimes when switching between pages, Next.js needs to download pages(chunks) from the server before rendering the page. (getInitialProps, getServerSideProps 등을 사용하는 페이지에서는 그렇습니다.) And it may also need to wait for the data. So while doing these tasks, the browser might be non responsive. (반응을 안 한다는 것은 그냥 흰색 페이지로 보여주는 것입니다.) We can simply fix this issue by showing a loading indicator. That's what this examples shows.

 

페이지를 이동할 때 사용하는 useRouter

 

  • routeChangeStart(url) - Fires when a route starts to change
  • routeChangeComplete(url) - Fires when a route changed completely
  • routeChangeError(err, url) - Fires when there's an error when changing routes, or a route load is cancelled
    • err.cancelled - Indicates if the navigation was cancelled
  • beforeHistoryChange(url) - Fires just before changing the browser's history
  • hashChangeStart(url) - Fires when the hash will change but not the page
  • hashChangeComplete(url) - Fires when the hash has changed but not the page

 

import Router from 'next/router'
import Link from 'next/link'
import Head from 'next/head'
import NProgress from 'nprogress'

Router.events.on('routeChangeStart', (url) => {
  console.log(`Loading: ${url}`)
  NProgress.start()
})
Router.events.on('routeChangeComplete', () => NProgress.done())
Router.events.on('routeChangeError', () => NProgress.done())

export default function App({ Component, pageProps }) {
  return (
    <>
      <Head>
        {/* Import CSS for nprogress */}
        <link rel="stylesheet" type="text/css" href="/nprogress.css" />
      </Head>
   .. 중략

 

https://github.com/harm-meijer/nextjs-example/blob/067daa8edaa4998c2a53879cd1f6da41660670f6/pages/_app.js

 

harm-meijer/nextjs-example

example app with nextjs. Contribute to harm-meijer/nextjs-example development by creating an account on GitHub.

github.com

 


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체