LoginSignup
12
6

More than 3 years have passed since last update.

【TypeScript】Next.jsにNProgressを導入する方法

Posted at

NProgressをインストールする

必要なモジュールをインストールします。

npm i nprogress @types/nextjs-progressbar

NProgess用のCSSをstaticフォルダに配置

以下から取ってこれます。
https://github.com/rstacruz/nprogress/blob/master/nprogress.css

/static/css/nprogress.css
/* Make clicks pass-through */
#nprogress {
  pointer-events: none;
}

#nprogress .bar {
  background: rgb(79, 214, 255);

  position: fixed;
  z-index: 1031;
  top: 0;
  left: 0;

  width: 100%;
  height: 3px;
}

/* Fancy blur effect */
#nprogress .peg {
  display: block;
  position: absolute;
  right: 0px;
  width: 100px;
  height: 100%;
  box-shadow: 0 0 10px rgb(79, 214, 255), 0 0 5px rgb(79, 214, 255);
  opacity: 1;

  -webkit-transform: rotate(3deg) translate(0px, -4px);
  -ms-transform: rotate(3deg) translate(0px, -4px);
  transform: rotate(3deg) translate(0px, -4px);
}

/* Remove these to get rid of the spinner */
#nprogress .spinner {
  display: block;
  position: fixed;
  z-index: 1031;
  top: 15px;
  right: 15px;
}

#nprogress .spinner-icon {
  width: 18px;
  height: 18px;
  box-sizing: border-box;

  border: solid 2px transparent;
  border-top-color: rgb(79, 214, 255);
  border-left-color: rgb(79, 214, 255);
  border-radius: 50%;

  -webkit-animation: nprogress-spinner 400ms linear infinite;
  animation: nprogress-spinner 400ms linear infinite;
}

.nprogress-custom-parent {
  overflow: hidden;
  position: relative;
}

.nprogress-custom-parent #nprogress .spinner,
.nprogress-custom-parent #nprogress .bar {
  position: absolute;
}

@-webkit-keyframes nprogress-spinner {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}
@keyframes nprogress-spinner {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

Routerにイベントを追加

CSSを読み込み、Routerにイベントを追加します。
共通Appバーにこの処理を書けば、全ての画面遷移でプログレスバーが表示されます。

AppBar.tsx

import React from "react";
import Router from "next/router";
import NProgress from "nprogress";
import Head from "next/head";

NProgress.configure({ showSpinner: false });

Router.events.on("routeChangeStart", () => {
  NProgress.start();
});

Router.events.on("routeChangeComplete", () => {
  NProgress.done();
});

Router.events.on("routeChangeError", () => {
  NProgress.done();
});

export default function Bar() {
  return (
    <div>
      <Head>
        <link
          rel="stylesheet"
          type="text/css"
          href="/static/css/nprogress.css"
        />
      </Head>
    </div>
  );
}

12
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
6