Oguzhan
Oguzhan

Reputation: 255

How to implement a loading page on route change in Nextjs 13?

I see that there were event handlers on route change in previous NextJS versions and they are no longer available with Next 13.

Some pages in my project take a couple of seconds to load and I want to display a loading component while the page is being loaded because it feels like there is nothing happening when user clicks on a Link element.

Is there a way to achieve this? Suspense didn't help.

This is my current app/(root)/layout.tsx

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <Head>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <body>
        <Script src="https://telegram.org/js/telegram-web-app.js" />
        <Providers>
            <Suspense fallback={<LoadingPage />}>
              <Header />
              {children}
              <NavigationBar />
            </Suspense>
        </Providers>
        <Toaster
          closeButton={false}
          position="bottom-center"
          toastOptions={{
            duration: 3000,
          }}
        />
      </body>
    </html>
  );
}

However, Suspense doesn't help at all.

Upvotes: 1

Views: 1811

Answers (1)

G&#252;nay Yağcı
G&#252;nay Yağcı

Reputation: 68

You can create a file named loading.js under the app folder. This runs the build on this page during route changes. This is a build that comes with the next 13. But its name should definitely be loading.

app>loading.js

const Loading = ()=>{
    return(
        <div>
            test Loading
        </div>
    )
}
export default Loading

Next13 app is valid for router. I would be happy if you let me know the result.

Upvotes: 3

Related Questions