use-container-queries
Version:
A react hook that tracks a containers size and the range that width falls into within a list of breakpoints. This allows better responsive styling, where the user can style DOM elements based on their container, rather than the browser viewport.
3 lines (2 loc) • 1.71 kB
JavaScript
Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");function r(){return(r=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}var t="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement?e.useLayoutEffect:e.useEffect;exports.useContainerQueries=function(n){var i=n.breakpoints,o=n.ignoreDimensions,a=void 0===o||o,u=Object.keys(i)[0],c=e.useState({activeBreakpoint:u,width:0}),s=c[0],v=c[1],l=e.useRef(null),d=e.useRef(null),f=e.useCallback((function(e,r){for(var t,n=0,o=Object.entries(i);n<o.length;n++){var a=o[n],u=a[0],c=a[1],s=c[1];if(r>=c[0]){if(void 0===s){t=u;break}if(r<=s){t=u;break}}}return{activeBreakpoint:t||e,width:r}}),[i]),b=e.useCallback((function(e){var t,n=e[0];if(t=n.borderBoxSize?Math.round(Array.isArray(n.borderBoxSize)?n.borderBoxSize[0].inlineSize:n.borderBoxSize.inlineSize):Math.round(n.contentRect.width),a){var i=f(s.activeBreakpoint,t).activeBreakpoint;i!==s.activeBreakpoint&&v((function(e){return r({},e,{activeBreakpoint:i})}))}else v(f(s.activeBreakpoint,t))}),[s.activeBreakpoint,a,f]);return t((function(){return l.current||(l.current=new ResizeObserver(b)),d.current&&l.current.observe(d.current,{box:"border-box"}),function(){var e;null==(e=l.current)||e.disconnect(),l.current=null}}),[b]),{ref:e.useCallback((function(e){var r,t;d.current&&(null==(r=l.current)||r.unobserve(d.current)),d.current=e,e&&(null==(t=l.current)||t.observe(e))}),[]),width:s.width,active:s.activeBreakpoint}};
//# sourceMappingURL=use-container-queries.cjs.production.min.js.map
;