Skip to content

Instantly share code, notes, and snippets.

@caseyyee
Created August 26, 2019 17:47
Show Gist options
  • Save caseyyee/d7457918730bce27863eb36424f9572a to your computer and use it in GitHub Desktop.
Save caseyyee/d7457918730bce27863eb36424f9572a to your computer and use it in GitHub Desktop.
JSX <Hide/> using styled-component and rebass.js
// https://gist.github.com/Kikobeats/0dbda3ec8154fa942dc47d36504681c6
import styled from "styled-components";
import theme from "./theme";
const { breakpoints } = theme;
const lastIndex = breakpoints.length - 1;
const getMediaBreakpoint = (breakpoints, breakpoint, index) => {
if (index === 0) return `@media screen and (max-width: ${breakpoint})`;
const prevBreakpoint = breakpoints[index - 1];
if (index === lastIndex) {
return `@media screen and (min-width: ${prevBreakpoint})`;
}
return `@media screen and (min-width: ${prevBreakpoint}) and (max-width: ${breakpoint})`;
};
const mediaBreakpoints = breakpoints.reduce((acc, breakpoint, index) => {
acc[index] = getMediaBreakpoint(breakpoints, breakpoint, index);
return acc;
}, {});
const hidden = key => props => {
const breakpoints = [].concat(props.breakpoints);
return breakpoints.includes(key)
? {
[mediaBreakpoints[key]]: {
display: "none"
}
}
: null;
};
const Hide = styled.span(
[],
...Object.keys(mediaBreakpoints).map(i => hidden(Number(i)))
);
export default Hide;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment