UNPKG

@retailmenot/anchor

Version:

A React UI Library by RetailMeNot

67 lines (66 loc) 2.68 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; // VENDOR import * as React from 'react'; import classNames from 'classnames'; import styled, { up, css, down, ThemeContext, } from '@xstyled/styled-components'; import { layout, space } from '@xstyled/system'; const { useContext } = React; const StyledParent = styled('div') ` ${layout} ${space} ${({ keys }) => keys.map((current, index) => { const next = keys[index + 1]; return css ` > :nth-child(${index + 1}) { ${next && up(next, css({ display: 'none' }))} ${current !== 'xs' && down(current, css({ display: 'none' }))} } `; })} `; /** * The purpose of Adapt is to display different content for different breakpoints. * It accomplishes this via media queries and display: none. It expects a forEach * prop object with values mapped to different breakpoints and children as a render * prop. It then renders the child function for each breakpoint, passing in the * associated value and the breakpoint as the first two arguments. * * Example usage: * <Adapt forEach={{ xs: 'apple', md: 'banana' }}> * {(value, breakpoint) => ( * <p> * {value} * </p> * )} * </Adapt> * * => * <p>apple</p> // displays below md breakpoint * <p>banana</p> // displays at and above md breakpoint */ export const Adapt = (_a) => { var { className, children, forEach } = _a, props = __rest(_a, ["className", "children", "forEach"]); const theme = useContext(ThemeContext); const breakpoints = theme && theme.breakpoints; const keys = Object.keys(forEach); // Keys are sorted by their pixel values (if available) so // that the css styles are ordered properly. // This could be changed to use ResponsiveContext's sorted breakpoints. const sortedKeys = breakpoints ? keys.sort((a, b) => (breakpoints[a] || 0) - (breakpoints[b] || 0)) : keys; const childs = keys.map(key => children(forEach[key], key)); return (React.createElement(StyledParent, Object.assign({ className: classNames('anchor-adapt', className), keys: sortedKeys }, props), childs)); }; Adapt.displayName = 'Adapt'; //# sourceMappingURL=Adapt.component.js.map