This repository was archived by the owner on Apr 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathMediaQuery.tsx
More file actions
69 lines (63 loc) · 1.72 KB
/
MediaQuery.tsx
File metadata and controls
69 lines (63 loc) · 1.72 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import React from "react";
import { PixelRatio, Platform, ScaledSize } from "react-native";
import useDimensions from "./useDimensions";
type Orientation = "landscape" | "portrait";
export interface IMediaQuery {
minHeight?: number;
maxHeight?: number;
minWidth?: number;
maxWidth?: number;
minAspectRatio?: number;
maxAspectRatio?: number;
minPixelRatio?: number;
maxPixelRatio?: number;
orientation?: Orientation;
condition?: boolean;
platform?: string;
}
export const isInInterval = (
value: number,
min?: number,
max?: number
): boolean =>
(min === undefined || value >= min) && (max === undefined || value <= max);
export const mediaQuery = (
dimensions: ScaledSize,
{
minWidth,
maxWidth,
minHeight,
maxHeight,
minAspectRatio,
maxAspectRatio,
orientation,
platform,
minPixelRatio,
maxPixelRatio,
condition
}: IMediaQuery
): boolean => {
const { width, height } = dimensions;
const currentOrientation: Orientation =
width > height ? "landscape" : "portrait";
return (
isInInterval(width, minWidth, maxWidth) &&
isInInterval(height, minHeight, maxHeight) &&
isInInterval(width / height, minAspectRatio, maxAspectRatio) &&
isInInterval(PixelRatio.get(), minPixelRatio, maxPixelRatio) &&
(orientation === undefined || orientation === currentOrientation) &&
(platform === undefined || platform === Platform.OS) &&
(condition === undefined || condition)
);
};
interface MediaQueryProps extends IMediaQuery {
children?: React.ReactNode;
}
export default ({ children, ...props }: MediaQueryProps) => {
const dimensions = useDimensions();
const val = mediaQuery(dimensions, props);
if (val) {
return children;
}
return null;
};