Created
November 6, 2020 13:17
-
-
Save YussufElarif/da787c2a88035e1e06dd5fe400df46ec to your computer and use it in GitHub Desktop.
React Responsive Hook
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'; | |
export enum DeviceEnum | |
{ | |
Desktop, | |
Tablet, | |
Mobile | |
} | |
export function useDevice() | |
{ | |
const [device, setDevice] = useState<DeviceEnum>(); | |
useEffect(() => | |
{ | |
handleResize(); | |
}, []); | |
useEffect(() => | |
{ | |
window.addEventListener('resize', handleResize); | |
return () => window.removeEventListener('resize', handleResize); | |
}, []); | |
function handleResize() | |
{ | |
// If width greater than tablet | |
if (window.innerWidth > 979) | |
{ | |
return setDevice(DeviceEnum.Desktop); | |
} | |
// If width greater than mobile | |
if (window.innerWidth > 500) | |
{ | |
return setDevice(DeviceEnum.Tablet); | |
} | |
return setDevice(DeviceEnum.Mobile); | |
} | |
return { | |
desktop: device === DeviceEnum.Desktop, | |
tablet: device === DeviceEnum.Tablet, | |
mobile: device === DeviceEnum.Mobile | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment