Skip to content

Instantly share code, notes, and snippets.

@duongdam
Created April 26, 2023 03:41
Show Gist options
  • Save duongdam/047b132c79f9b52f08efad71f9382e59 to your computer and use it in GitHub Desktop.
Save duongdam/047b132c79f9b52f08efad71f9382e59 to your computer and use it in GitHub Desktop.
Next js detect devices (mobile, pc, android, ios, ssr, windown)
import {useEffect} from 'react'
const getDevices = (userAgent: NavigatorID['userAgent']) => {
const isAndroid = () => Boolean(userAgent.match(/Android/i))
const isIos = () => Boolean(userAgent.match(/iPhone|iPad|iPod/i))
const isOpera = () => Boolean(userAgent.match(/Opera Mini/i))
const isWindows = () => Boolean(userAgent.match(/IEMobile/i))
const isSSR = () => Boolean(userAgent.match(/SSR/i))
const isMobile = () => Boolean(isAndroid() || isIos() || isOpera() || isWindows())
const isDesktop = () => Boolean(!isMobile() && !isSSR())
return {
isMobile,
isDesktop,
isAndroid,
isIos,
isSSR,
}
}
const useDevices = () => {
useEffect(() => {
}, [])
const userAgent = typeof navigator === 'undefined' ? 'SSR' : navigator.userAgent
return getDevices(userAgent)
}
export default useDevices
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment