-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathuseOrientationChange.js
More file actions
35 lines (34 loc) · 1.31 KB
/
Copy pathuseOrientationChange.js
File metadata and controls
35 lines (34 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React, { useCallback, useEffect, useState } from "react";
import { isMobile } from "../../lib/selectors";
export function useMobileOrientation() {
if (typeof window === 'undefined') return;
const [state, setState] = useState(() => {
const orientation = window.innerWidth > window.innerHeight ? 90 : 0;
return {
isPortrait: orientation === 0,
isLandscape: orientation === 90,
orientation: orientation === 0 ? 'portrait' : 'landscape'
}
});
const handleOrientationChange = useCallback(() => {
const orientation = window.innerWidth > window.innerHeight ? 90 : 0;
const next = {
isPortrait: orientation === 0,
isLandscape: orientation === 90,
orientation: orientation === 0 ? 'portrait' : 'landscape'
}
state.orientation !== next.orientation && setState(next);
}, [state.orientation]);
useEffect(() => {
if (typeof window !== undefined && isMobile) {
handleOrientationChange();
window.addEventListener("load", handleOrientationChange, false);
window.addEventListener("resize", handleOrientationChange, false);
}
return () => {
window.removeEventListener("resize", handleOrientationChange, false);
window.removeEventListener("load", handleOrientationChange, false);
}
}, [handleOrientationChange]);
return state;
}