forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseOrientation.ts
51 lines (41 loc) · 1.1 KB
/
useOrientation.ts
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* eslint-disable */
import { useEffect, useState } from 'react';
import { off, on } from './util';
export interface OrientationState {
angle: number;
type: string;
}
const defaultState: OrientationState = {
angle: 0,
type: 'landscape-primary',
};
const useOrientation = (initialState: OrientationState = defaultState) => {
const [state, setState] = useState(initialState);
useEffect(() => {
let mounted = true;
const onChange = () => {
if (mounted) {
const { orientation } = screen as any;
if (orientation) {
const { angle, type } = orientation;
setState({ angle, type });
} else if (window.orientation) {
setState({
angle: typeof window.orientation === 'number' ? window.orientation : 0,
type: '',
});
} else {
setState(initialState);
}
}
};
on(window, 'orientationchange', onChange);
onChange();
return () => {
mounted = false;
off(window, 'orientationchange', onChange);
};
}, []);
return state;
};
export default useOrientation;