Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement loading screen in Next.js

I am new in nextjs and using nextjs v9.3, next-redux-wrapper v5, @material-ui/core v4.2, and custom express server.

I am trying to implement a loading screen when changing routes in my Nextjs app so I am using framer motion for transition between page and works fine but now how can use loading component when changing routes?

My current implementation is as follows:

_app.js

import React, { useEffect } from "react";
import { ThemeProvider } from "@material-ui/core/styles";
import { CssBaseline } from "@material-ui/core";
import { theme } from "../lib/theme";
import withRedux from "next-redux-wrapper";
import { Provider } from "react-redux";
import reduxStore from "../store/store";
import { PersistGate } from "redux-persist/integration/react";
import { AnimatePresence } from "framer-motion";
import Navbar from "../components/Navbar";
import Meta from "../components/Meta";

function MyApp(props) {
  useEffect(() => {
    const jssStyles = document.querySelector("#jss-server-side");
    if (jssStyles && jssStyles.parentNode)
      jssStyles.parentNode.removeChild(jssStyles);
  }, []);
  const { Component, pageProps, store, router } = props;
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Provider store={store}>
        <PersistGate persistor={store.__PERSISTOR} loading={null}>
          <Meta/>
          <Navbar {...props} />
          <AnimatePresence exitBeforeEnter>
            <Component {...pageProps} key={router.route}/>
          </AnimatePresence>
        </PersistGate>
      </Provider>
    </ThemeProvider>
  );
}

export default withRedux(reduxStore)(MyApp);

UPDATE

                           `___-_-_-_-_my solution_-_-_-_-___`

method 1 : in next.js v9.3 when I used framer-motion

import React, {
  useEffect,
  useState,
} from "react";
import { ThemeProvider as MaterialThemeProvider } from "@material-ui/core/styles";
import { ThemeProvider as StyledThemeProvider } from "styled-components";
import { CssBaseline } from "@material-ui/core";
import { AnimatePresence, motion } from "framer-motion";
import theme from "../lib/theme";
import Layout from "../components/Layout";
import Loader from "react-loader-spinner";

function MyApp(props) {
  const { Component, pageProps, router } = props;
  // blow useState & useEffect for tracking change route
  const [isRouteChanging, setIsRouteChanging] = useState(false);
  useEffect(() => {
    const routeChangeStartHandler = () => setIsRouteChanging(true);

    const routeChangeEndHandler = () => setIsRouteChanging(false);

    router.events.on("routeChangeStart", routeChangeStartHandler);
    router.events.on("routeChangeComplete", routeChangeEndHandler);
    router.events.on("routeChangeError", routeChangeEndHandler);
    return () => {
      router.events.off("routeChangeStart", routeChangeStartHandler);
      router.events.off("routeChangeComplete", routeChangeEndHandler);
      router.events.off("routeChangeError", routeChangeEndHandler);
    };
  }, []);

  // useEffect config material-ui
  useEffect(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector("#jss-server-side");
    if (jssStyles && jssStyles.parentNode)
      jssStyles.parentNode.removeChild(jssStyles);
  }, []);

  return (
    <StyledThemeProvider theme={theme}>
      <MaterialThemeProvider theme={theme}>
        <CssBaseline />
        {/*animation for each page when route changes*/}
        <Layout>
          {isRouteChanging ? (
            <motion.div
              initial={{
                opacity: 0,
                height: "90vh",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
              animate={{
                opacity: 1,
              }}
              exit={{
                opacity: 0,
              }}
            >
              <Loader
                type="Grid"
                color={theme.spinnerColor}
                height={80}
                width={80}
              />
            </motion.div>
          ) : (
            <AnimatePresence exitBeforeEnter>
              <Component {...pageProps} key={router.route} />
            </AnimatePresence>
          )}
        </Layout>
      </MaterialThemeProvider>
    </StyledThemeProvider>
  );
}

export default MyApp;

method 2 : in next.js v10 and higher I used "nprogress": "^0.2.0"

import React, { useEffect } from "react";
import Router from "next/router";
// MUI Core
import CssBaseline from "@material-ui/core/CssBaseline";
import { ThemeProvider } from "@material-ui/core/styles";
// Utils
import theme from "Utils/theme";
// NProgress
import NProgress from "nprogress";

//Binding events.
Router.events.on("routeChangeStart", () => NProgress.start());
Router.events.on("routeChangeComplete", () => NProgress.done());
Router.events.on("routeChangeError", () => NProgress.done());


function MyApp({ Component, pageProps}) {

  // useEffect config material-ui
  useEffect(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector("#jss-server-side");
    if (jssStyles && jssStyles.parentNode)
      jssStyles.parentNode.removeChild(jssStyles);
  }, []);

  return (
    <Provider store={store}>
      <ThemeProvider theme={theme}>
              <CssBaseline />
              <Component {...pageProps} />
      </ThemeProvider>
    </Provider>
  );
}

export default MyApp;
like image 760
hamed hatami Avatar asked Apr 13 '20 09:04

hamed hatami


People also ask

How do I make a next JavaScript loading screen?

First we are going to create loader. js in /src that will content a CSS of our loader. You can paste the following content: Secondly we need to inject this CSS code into the header of our application so that it is loaded by the browser as quickly as possible.

How do I add a loader to NextJS?

NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. Approach: To add our spinner loader we are going to use the react-loader-spinner package. The react-loader-spinner package helps us to integrate spinner loader in our app.

Does NextJS support lazy loading?

Next. js supports lazy loading external libraries with import() and React components with next/dynamic .


1 Answers

I did it in this way. In _app.tsx:

import { useRouter } from 'next/router';

const MyApp = ({
  MainComponent, 
  pageProps,
}) => {    
const router = useRouter();
    const [pageLoading, setPageLoading] = React.useState<boolean>(false);
    React.useEffect(() => {
        const handleStart = () => { setPageLoading(true); };
        const handleComplete = () => { setPageLoading(false); };
    
        router.events.on('routeChangeStart', handleStart);
        router.events.on('routeChangeComplete', handleComplete);
        router.events.on('routeChangeError', handleComplete);
      }, [router]);

return (
  ...
  { pageLoading 
    ? (<div>Loading</div>)
    : <MainComponent {...pageProps} />
  }
  ...

)

}
like image 169
Siamko Avatar answered Oct 26 '22 23:10

Siamko