-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathHidden.tsx
More file actions
72 lines (60 loc) · 1.88 KB
/
Hidden.tsx
File metadata and controls
72 lines (60 loc) · 1.88 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
70
71
72
import { useMediaQuery, useTheme } from '@mui/material';
import React, { useMemo } from 'react';
type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl';
export interface HiddenProps {
children?: React.ReactNode;
only?: Breakpoint | Breakpoint[];
xsUp?: boolean;
smUp?: boolean;
mdUp?: boolean;
lgUp?: boolean;
xlUp?: boolean;
xsDown?: boolean;
smDown?: boolean;
mdDown?: boolean;
lgDown?: boolean;
xlDown?: boolean;
}
const BREAKPOINTS: Breakpoint[] = ['xs', 'sm', 'md', 'lg', 'xl'];
const extractCondition = (mediaQuery: string) =>
mediaQuery.replace(/^@media\s*/i, '');
export const Hidden = ({
children,
only,
xsUp = false,
smUp = false,
mdUp = false,
lgUp = false,
xlUp = false,
xsDown = false,
smDown = false,
mdDown = false,
lgDown = false,
xlDown = false
}: HiddenProps) => {
const theme = useTheme();
const mediaQuery = useMemo(() => {
const onlyValues = Array.isArray(only) ? only : only ? [only] : [];
const upProps: Record<Breakpoint, boolean> = { xs: xsUp, sm: smUp, md: mdUp, lg: lgUp, xl: xlUp };
const downProps: Record<Breakpoint, boolean> = { xs: xsDown, sm: smDown, md: mdDown, lg: lgDown, xl: xlDown };
const conditions: string[] = [];
for (const bp of BREAKPOINTS) {
if (onlyValues.includes(bp)) {
conditions.push(extractCondition(theme.breakpoints.only(bp)));
}
if (upProps[bp]) {
conditions.push(extractCondition(theme.breakpoints.up(bp)));
}
if (downProps[bp]) {
conditions.push(extractCondition(theme.breakpoints.down(bp)));
}
}
return conditions.length > 0 ? `@media ${conditions.join(', ')}` : '@media not all';
}, [only, xsUp, smUp, mdUp, lgUp, xlUp, xsDown, smDown, mdDown, lgDown, xlDown, theme.breakpoints]);
const matches = useMediaQuery(mediaQuery);
if (matches) {
return null;
}
return <>{children}</>;
};
export default Hidden;