@react-hook/size
Version:
A React hook for measuring the size of HTML elements including when they change
45 lines (34 loc) • 2.78 kB
JavaScript
;
exports.__esModule = true;
exports.default = void 0;
var React = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("react"));
var _resizeObserver = /*#__PURE__*/_interopRequireDefault( /*#__PURE__*/require("@react-hook/resize-observer"));
var _passiveLayoutEffect = /*#__PURE__*/_interopRequireDefault( /*#__PURE__*/require("@react-hook/passive-layout-effect"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/**
* A React hook for measuring the size of HTML elements including when they change
*
* @param target A React ref created by `useRef()` or an HTML element
* @param options Configures the initial width and initial height of the hook's state
*/
const useSize = (target, options) => {
const [size, setSize] = React.useState(() => {
var _options$initialWidth, _options$initialHeigh;
const targetEl = target && 'current' in target ? target.current : target;
return targetEl ? [targetEl.offsetWidth, targetEl.offsetHeight] : [(_options$initialWidth = options === null || options === void 0 ? void 0 : options.initialWidth) !== null && _options$initialWidth !== void 0 ? _options$initialWidth : 0, (_options$initialHeigh = options === null || options === void 0 ? void 0 : options.initialHeight) !== null && _options$initialHeigh !== void 0 ? _options$initialHeigh : 0];
});
(0, _passiveLayoutEffect.default)(() => {
const targetEl = target && 'current' in target ? target.current : target;
if (!targetEl) return;
setSize([targetEl.offsetWidth, targetEl.offsetHeight]);
}, [target]); // Where the magic happens
(0, _resizeObserver.default)(target, entry => {
const target = entry.target;
setSize([target.offsetWidth, target.offsetHeight]);
});
return size;
};
var _default = useSize;
exports.default = _default;