본문 바로가기
✘✘✘ Javascript

[event] window.matchMedia - mobile detecting: 모바일 확인 하기 + React Hook

by PrettyLog 2023. 4. 6.

1. javascript

  • window.innerWidth and window.innerHeight: to get size of mobile device
  • navigator.userAgent : To check if a device is a mobile device
function isMobileDevice() {
  const userAgent = navigator.userAgent;
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
}

function getScreenSize() {
  const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  const height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  return { width, height };
}

console.log("Is mobile device:", isMobileDevice());
console.log("Screen size:", getScreenSize());

2. CSS Media Queries:

/* Default styles for desktop */
body {
  background-color: blue;
}

/* Styles for mobile devices */
@media only screen and (max-width: 767px) {
  body {
    background-color: green;
  }
}

3. window.matchMedia():

  • check if the device is a mobile device based on the screen width
function isMobileDevice() {
    const mobileMediaQuery = '(max-width: 767px)'; // Adjust the breakpoint according to your needs
    const match = window.matchMedia(mobileMediaQuery);
       return match.matches;
}
console.log("Is mobile device:", isMobileDevice());
  • add event listener on matchMedia
    add event listeners that react to changes in the screen size, which is useful when you want to execute JavaScript code based on media query changes:
const mobileMediaQuery = '(max-width: 767px)';
const match = window.matchMedia(mobileMediaQuery);

function handleMediaChange(event) {
  if (event.matches) {
    console.log('Mobile device detected');
  } else {
    console.log('Desktop device detected');
  }
}

// Listen for media query changes
match.addListener(handleMediaChange);

// Call the function initially to detect the device type on page load
handleMediaChange(match);

4. React hook

  • useIsMobileDevice.ts hook
import { useState, useEffect } from 'react';

function useIsMobileDevice(breakpoint: number = 767): boolean {
  const [isMobile, setIsMobile] = useState<boolean>(false);

  useEffect(() => {
    const mobileMediaQuery = `(max-width: ${breakpoint}px)`;
    const match = window.matchMedia(mobileMediaQuery);

    function handleMediaChange(event: MediaQueryListEvent): void {
      setIsMobile(event.matches);
    }

    match.addEventListener('change', handleMediaChange);
    handleMediaChange(match);

    return () => {
      match.removeEventListener('change', handleMediaChange);
    };
  }, [breakpoint]);

  return isMobile;
}

export default useIsMobileDevice;
  • App.tsx
import React from 'react';
import useIsMobileDevice from './useIsMobileDevice'; // Import the custom hook

const App: React.FC = () => {
  const isMobile = useIsMobileDevice(); // Use the custom hook

  return (
    <div>
      <h1>Device Type: {isMobile ? 'Mobile' : 'Desktop'}</h1>
    </div>
  );
}

export default App;

match.addEventListener(callback) vs match.addEventListener('resize', callback)

The main differences in TypeScript is:

Define type annotations for the function parameters and return values.
Use match.addEventListener('change', handleMediaChange) and match.removeEventListener('change', handleMediaChange) >instead of the deprecated addListener and removeListener methods, which are not supported in TypeScript's >MediaQueryList type.

댓글