1

Preface

The next.js framework is a mainstream SSR framework. The powerful out-of-the-box and the very active community make it stand out among many frameworks. Recently, I wrote this article in order to realize the jumping back and forth between the next.js pages and the loading effect to improve the user experience. I hope it can help everyone.

operate

First, let’s analyze the implementation principle. First, there must be a monitoring event for the start and end of the jump between routes. The router monitoring event
image.png

With monitoring events, we can control the jump between pages very well.

@tanem/react-nprogress top of the page, here we will use the plug-in .

yarn add @tanem/react-nprogress

image.png

Next, we open this address and copy the code inside to our project.

1. Create new globalLoading.js

import React from 'react';
import { useNProgress } from '@tanem/react-nprogress';
const GlobalLoading = ({ isRouteChanging, }) => {
  const { animationDuration, isFinished, progress } = useNProgress({
    isAnimating: isRouteChanging,
  })

  return (
    <>
      <style jsx>{`
        .container {
          opacity: ${isFinished ? 0 : 1};
          pointerevents: none;
          transition: opacity ${animationDuration}ms linear;
        }
        .bar {
          background: #29d;
          height: 2px;
          left: 0;
          margin-left: ${(-1 + progress) * 100}%;
          position: fixed;
          top: 0;
          transition: margin-left ${animationDuration}ms linear;
          width: 100%;
          z-index: 1031;
        }
        .spinner {
          box-shadow: 0 0 10px #29d, 0 0 5px #29d;
          display: block;
          height: 100%;
          opacity: 1;
          position: absolute;
          right: 0;
          transform: rotate(3deg) translate(0px, -4px);
          width: 100px;
        }
      `}</style>
      <div className="container">
        <div className="bar">
          <div className="spinner" />
        </div>
      </div>
    </>
  )
};

export default GlobalLoading;

2. Modify _app.js

const MyApp = ({Component, pageProps}) => {
  const router = useRouter()

  const [state, setState] = useState({
    isRouteChanging: false,
    loadingKey: 0,
  })

  useEffect(() => {
    const handleRouteChangeStart = () => {
      setState((prevState) => ({
        ...prevState,
        isRouteChanging: true,
        loadingKey: prevState.loadingKey ^ 1,
      }))
    }

    const handleRouteChangeEnd = () => {
      setState((prevState) => ({
        ...prevState,
        isRouteChanging: false,
      }))
    }

    router.events.on('routeChangeStart', handleRouteChangeStart)
    router.events.on('routeChangeComplete', handleRouteChangeEnd)
    router.events.on('routeChangeError', handleRouteChangeEnd)

    return () => {
      router.events.off('routeChangeStart', handleRouteChangeStart)
      router.events.off('routeChangeComplete', handleRouteChangeEnd)
      router.events.off('routeChangeError', handleRouteChangeEnd)
    }
  }, [router.events])

  return <>
    <GlobalLoading isRouteChanging={state.isRouteChanging} key={state.loadingKey} />
    <Component {...pageProps} />
  </>
}

export default wrapper.withRedux(MyApp)

This completes the writing of all the code, and then we run the next project to see if switching back and forth between pages has the effect of the loading bar.
image.png

Nice!

Demo address

Summarize

Understand the implementation principle plus the contributions of the community's great people. Remember to go to the next.js official website to see the latest trends and new features added in the new version, such as the recent addition of middleware features in next.js 12.

Quote

next.js loading bar video tutorial
next.js middleware


Awbeci
3.1k 声望213 粉丝

Awbeci