Created
August 18, 2020 13:08
-
-
Save gusfune/1ae54acc09c98554f09559b9777dfcf2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* useOrientation custom hook | |
* Usage: | |
* const { orientation } = useOrientation(); | |
*/ | |
import { useState, useEffect } from "react" | |
const useOrientation = () => { | |
const [orientation, setOrientation] = useState< | |
"portrait" | "landscape" | undefined | |
>("portrait") | |
let width: number | |
let height: number | |
const initialSetup = () => { | |
if (typeof window !== `undefined`) { | |
width = window.innerWidth | |
height = window.innerHeight | |
setOrientation(width / height >= 1 ? "landscape" : "portrait") | |
} | |
} | |
const listener = () => { | |
if (typeof window === "undefined" || !window.document) { | |
width = 0 | |
height = 0 | |
} else { | |
width = window.innerWidth | |
height = window.innerHeight | |
} | |
setOrientation(width / height >= 1 ? "landscape" : "portrait") | |
} | |
useEffect(() => { | |
initialSetup() | |
window.addEventListener("resize", listener) | |
return () => { | |
window.removeEventListener("resize", listener) | |
} | |
}, [initialSetup]) | |
return { | |
orientation, | |
} | |
} | |
export { useOrientation } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment