Skip to content

Commit 9419658

Browse files
committed
add useMobileOrientation hook
1 parent c528083 commit 9419658

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

index.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ declare namespace ReactDeviceDetect {
8484

8585
export function withOrientationChange<P, S = {}>(Component: React.Component<P, S> | React.FC<P>): React.ComponentClass<P, S>;
8686

87+
export function useMobileOrientation(): { isPortrait: boolean, isLandscape: boolean, orientation: 'portrait' | 'landscape' };
88+
8789
export class BrowserView extends React.Component<ViewProps> {
8890
}
8991

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import React, { useCallback, useEffect, useState } from "react";
2+
import { isMobile } from "./selectors";
3+
4+
export function useMobileOrientation() {
5+
const [state, setState] = useState(() => {
6+
const orientation = window.innerWidth > window.innerHeight ? 90 : 0;
7+
return {
8+
isPortrait: orientation === 0,
9+
isLandscape: orientation === 90,
10+
orientation: orientation === 0 ? 'portrait' : 'landscape'
11+
}
12+
});
13+
const handleOrientationChange = useCallback(() => {
14+
const orientation = window.innerWidth > window.innerHeight ? 90 : 0;
15+
const next = {
16+
isPortrait: orientation === 0,
17+
isLandscape: orientation === 90,
18+
orientation: orientation === 0 ? 'portrait' : 'landscape'
19+
}
20+
state.orientation !== next.orientation && setState(next);
21+
}, [state.orientation]);
22+
useEffect(() => {
23+
if (typeof window !== undefined && isMobile) {
24+
handleOrientationChange();
25+
window.addEventListener("load", handleOrientationChange, false);
26+
window.addEventListener("resize", handleOrientationChange, false);
27+
}
28+
return () => {
29+
window.removeEventListener("resize", handleOrientationChange, false);
30+
window.removeEventListener("load", handleOrientationChange, false);
31+
}
32+
}, [handleOrientationChange]);
33+
return state;
34+
}
35+
36+
export { useMobileOrientation };

0 commit comments

Comments
 (0)