Skip to content

Instantly share code, notes, and snippets.

@zeckdude
Created July 5, 2022 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeckdude/93d6de00621194ed72313c20607df75c to your computer and use it in GitHub Desktop.
Save zeckdude/93d6de00621194ed72313c20607df75c to your computer and use it in GitHub Desktop.
Hidden component to hide contents at specified MUI breakpoints
import { FC } from 'react';
import { css } from '@emotion/react';
import { useTheme, Breakpoint, Box } from '@mui/material';
interface HiddenProps extends BoxProps {
xsDown?: boolean;
xsUp?: boolean;
smDown?: boolean;
smUp?: boolean;
mdDown?: boolean;
mdUp?: boolean;
lgDown?: boolean;
lgUp?: boolean;
xlDown?: boolean;
xlUp?: boolean;
only?: Breakpoint | Breakpoint[];
className?: string;
}
export const Hidden: FC<HiddenProps> = (props) => {
const {
children,
className,
only,
} = props;
const theme = useTheme();
let boxStyleString = '';
for (let i = 0; i < theme.breakpoints.keys.length; i += 1) {
const breakpoint = theme.breakpoints.keys[i];
const breakpointUp = props[`${breakpoint}Up`];
const breakpointDown = props[`${breakpoint}Down`];
if (breakpointUp) {
boxStyleString += `${theme.breakpoints.up(breakpoint)} {
display: none;
}`;
}
if (breakpointDown) {
boxStyleString += `${theme.breakpoints.down(breakpoint)} {
display: none;
}`;
}
}
if (only) {
const onlyBreakpoints = Array.isArray(only) ? only : [only];
onlyBreakpoints.forEach((breakpoint) => {
boxStyleString += `${theme.breakpoints.only(breakpoint)} {
display: none;
}`;
});
}
if (process.env.ENV !== 'production' && boxStyleString === '') {
console.error(`Breakpoint props not received on \`<Hidden />\``);
}
return (
<Box
css={css`
${boxStyleString}
`}
className={className}
>
{children}
</Box>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment