1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Next.js で画面サイズを取得する方法

Last updated at Posted at 2021-12-02

本記事では、Next.jsで動的に画面サイズを取得するHooksをご紹介します。

レイアウトの調整にはFlexboxやCSS Gridを使用することが多いと思います。
しかし、コンポーネントのレイアウトを実装するときにどうしてもウィンドウサイズから計算しなければならない場合もあります。
そういった場合に使用できるHooksをご紹介させていただきます。

Hooksの実装

GetWindowSize.ts

import { useEffect, useState } from "react";

export const getWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: 0,
    height: 0,
  });

  useEffect(() => {
    if (typeof window !== "undefined") {
      const handleResize = () => {
        setWindowSize({
          width:
           window.innerWidth,
          height: window.innerHeight,
        });
      };

      window.addEventListener("resize", handleResize);
      handleResize();
      return () => window.removeEventListener("resize", handleResize);
    } else {
      return;
    }
  }, []);
  return windowSize;
};

Next.js はPre-redndering(SSR,SSG)がサポートされているので、
Hooksでブラウザ側にしか存在しないグローバルオブジェクトのwindowやdocumentを参照する場合には必ず

if (typeof window !== "undefined") {

を実装するようにしましょう。

使い方

index.tsx

import type { NextPage } from "next";
import { getWindowSize } from "../hooks/GetWindowSize";

const Home: NextPage = () => {
  const { height, width } = getWindowSize();
  return (
    <div>
      height:{height} width:{width}
    </div>
  );
};

export default Home;

まとめ

Next.jsでウィンドウサイズを取得したいときにはWindow: resize イベントを利用したHooksを実装する!
ただし、windowがundefinedの可能性があることに注意!

Ignite UI for React トライアル版を利用するには

Ignite UI for React はトライアル板での試用が可能です。
トライアルのダウンロードはこちら
また、こちらのページよりアカウントの作成を行っていただくと登録より30日間、弊社のテクニカルサポートをご利用いただくことが出来ますのでお気軽にお問い合わせください。

製品をご購入をご検討のお客様はこちらのページよりお気軽にお問い合わせください。そのほか、製品デモや、弊社製品そのものに関するご相談だけでなく、システム開発における様々なご相談も実施可能な無料相談会も随時受け付けています。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?