0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Web】画面サイズによって使用するコンポーネントを切り替える方法

Posted at

はじめに

最近はもっぱらWebの開発に勤しんでいます。
TypeScript、Reactの組み合わせで開発していますが、先日レスポンシブ対応の一環で画面サイズによってUIを切り替える必要が出てきました。
その際実装方法を調べて実装したのですが、利用頻度の多い実装なので備忘録の為に実装方法を残しておきたいと思います。

実装方法

まず、表示している画面サイズを調べ返却する為のカスタムフックを作成します。

useWindowSize.tsx
import { useState, useEffect } from "react";

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

  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    window.addEventListener("resize", handleResize);
    handleResize();

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

  return windowSize;
};

export default useWindowSize;

useEffect内ではウィンドウサイズが変更される度に実行され、最後メモリーリーク防止の為コンポーネントがアンマウントされたときにイベントリスナーを削除するようにしています。

また、初回レンダリング時に一度だけ呼び出されるよう、Listenerに登録後handleResizeを呼び出すようにしています。

次に上記を利用する際のサンプルです。

ProfileCard.tsx
import useWindowSize from "@/hooks/useWindowSize";
import ProfilePC from "./ProfilePC";
import ProfileMobile from "./ProfileMobile";

const ProfileCard = () => {
  const { width } = useWindowSize();
  const isMobile = width < 768; 

  return isMobile ? <ProfileMobile /> : <ProfilePC />;
};

export default ProfileCard;

利用方法としては以上になります。
useWindowSizeを通して画面サイズを取得し、比較してコンポーネントを使い分けるようにしています。

さいごに

花粉がとんでもない量飛んでいそうですね、早めに薬を飲み始めていたのですがそれでも目が痒すぎる・・・

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?