Created
October 22, 2024 07:49
-
-
Save wolfcoder/1192bf99d69ae5a60e1a07112ef0c984 to your computer and use it in GitHub Desktop.
React hook device detection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
const useDeviceDetection = () => { | |
const [device, setDevice] = useState(''); | |
useEffect(() => { | |
const handleDeviceDetection = () => { | |
const userAgent = navigator.userAgent.toLowerCase(); | |
const isMobile = | |
/iphone|ipad|ipod|android|blackberry|windows phone/g.test(userAgent); | |
const isTablet = | |
/(ipad|tablet|playbook|silk)|(android(?!.*mobile))/g.test(userAgent); | |
if (isMobile) { | |
setDevice('Mobile'); | |
} else if (isTablet) { | |
setDevice('Tablet'); | |
} else { | |
setDevice('Desktop'); | |
} | |
}; | |
handleDeviceDetection(); | |
window.addEventListener('resize', handleDeviceDetection); | |
return () => { | |
window.removeEventListener('resize', handleDeviceDetection); | |
}; | |
}, []); | |
return device; | |
}; | |
export default useDeviceDetection; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment