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?

More than 3 years have passed since last update.

React入門 - Tips10 - useMediaQueryでレスポンシブ対応

Last updated at Posted at 2021-06-18

目次

useMediaQuery

pcとスマートフォンでの表示切替が必要な時に使用します。

実装方法(useMediaQueryのhook)

use-media-query.tsx
import { useEffect, useState } from 'react'

export const useMedia = () => {
  const queryStrings = {
    pc: 'screen and (min-width: 768px)',
    sp: 'screen and (max-width: 767px)',
    short: 'screen and (max-height: 480px)',
  };
  const [test, setTest] = useState(null);

  useEffect(() => {
    let timeout;
    const onResize = () => {
      if (timeout) return
      if (typeof window === "undefined") {
        setTest(null);
      } else {
        setTest( Object.fromEntries(
          Object.entries(queryStrings).map(([k, v]: [string, string]) => [
            k,
            window.matchMedia(v),
          ])
        ));
      }
      timeout = setTimeout(() => timeout = null, 500)
    }

    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  })  

  return test;
};

実装方法(コンポーネント側)

media-query-test.tsx
import React, {useMemo} from 'react'
import {useMedia} from './use-media-query';

export const Comp:React.FC = (props) => {
  const media = useMedia();
  const isSP =  media ? media.sp.matches : false;

  return <span>現在は{isSP ? "SP" : "PC"}で表示しています</span>
}

export default Comp

まとめ

動かしてみてください。
ブラウザの幅を変えると表示が変わると思います。
割と簡単に実装出来ました。

ちょっと調べたら、こんな感じのreact-responseなるものでもっと簡単に
実装可能みたいです。試してないけど。

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?