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

useMediaQueryのTips

Posted at

1.タッチデバイスであるか

export const isTouchDevice(){
  return window.matchMedia('(hover: none)').matches;
}

2.useMediaQueryフック

'use client';

import { useState, useEffect } from 'react';

export const useMediaQuery = (query: string) => {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const mediaQueryList = window.matchMedia(query);
    setMatches(mediaQueryList.matches);

    const handleChange = (e: MediaQueryListEvent) => {
      setMatches(e.matches);
    };

    mediaQueryList.addEventListener('change', handleChange);

    return () => {
      mediaQueryList.removeEventListener('change', handleChange);
    };
  }, [query]);

  return matches;
};
  • SP、Tablet、PCの判断
const isSp = !useMediaQuery('(min-width: 768px)');
const isPc = useMediaQuery('(min-width: 1024px)');
const isTablet = useMediaQuery('(min-width: 768px)') && !isPc;

参考記事

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