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.
'✘✘✘ Javascript' 카테고리의 다른 글
[axios] Query params 자동 인코딩 Query string > params are encoded automatically (0) | 2023.04.10 |
---|---|
Javascript Falsy values 값들 (0) | 2023.04.09 |
How to detect text overflow ellipsis? (0) | 2023.01.09 |
Capitalize first letter (0) | 2023.01.09 |
[Javascript] Promise.allSettled vs Promise.all, Promise (0) | 2023.01.07 |
댓글