-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathHidden.tsx
More file actions
88 lines (76 loc) · 2.18 KB
/
Hidden.tsx
File metadata and controls
88 lines (76 loc) · 2.18 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { useMediaQuery, useTheme } from '@mui/material';
import React, { useMemo } from 'react';
type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl';
const BREAKPOINTS: Breakpoint[] = ['xs', 'sm', 'md', 'lg', 'xl'];
const extractCondition = (mediaQuery: string) => mediaQuery.replace(/^@media\s*/i, '');
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;
}
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 onlyKey = Array.isArray(only) ? [...only].sort().join(',') : only ?? '';
const mediaQuery = useMemo(() => {
const onlyValues = onlyKey ? (onlyKey.split(',') as Breakpoint[]) : [];
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 breakpoint of BREAKPOINTS) {
if (onlyValues.includes(breakpoint)) {
conditions.push(extractCondition(theme.breakpoints.only(breakpoint)));
}
if (upProps[breakpoint]) {
conditions.push(extractCondition(theme.breakpoints.up(breakpoint)));
}
if (downProps[breakpoint]) {
conditions.push(
extractCondition(
breakpoint === 'xs' ? theme.breakpoints.only('xs') : theme.breakpoints.down(breakpoint)
)
);
}
}
return conditions.length > 0 ? `@media ${conditions.join(', ')}` : '@media not all';
}, [onlyKey, 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;