UNPKG

react-aspect-ratio

Version:

React Component to maintain a consistent width-to-height ratio (aspect ratio), preventing cumulative layout shift.

61 lines (58 loc) 2.33 kB
"use strict"; exports.__esModule = true; exports.default = void 0; var _react = require("react"); var _jsxRuntime = require("react/jsx-runtime"); var _excluded = ["className", "children", "ratio", "style"]; function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; } var CUSTOM_PROPERTY_NAME = '--aspect-ratio'; var DEFAULT_CLASS_NAME = 'react-aspect-ratio-placeholder'; class AspectRatio extends _react.Component { constructor() { super(...arguments); this.node = null; this.setNode = node => { this.node = node; }; } componentDidUpdate() { if (this.node) { var { node } = this; // BC for older version of React https://github.com/facebook/react/issues/6411 // check if React support custom property AFTER var customPropertyValue = node.style.getPropertyValue(CUSTOM_PROPERTY_NAME); if (!customPropertyValue) { node.style.setProperty(CUSTOM_PROPERTY_NAME, "(" + this.props.ratio + ")"); } } } render() { var _this$props = this.props, { className, children, ratio, style } = _this$props, restProps = _objectWithoutPropertiesLoose(_this$props, _excluded); // eslint-disable-line no-unused-vars var newStyle = _extends({}, style, { // https://github.com/roderickhsiao/react-aspect-ratio/commit/53ec15858ae186c41e70b8c14cc5a5b6e97cb6e3 [CUSTOM_PROPERTY_NAME]: "(" + ratio + ")" }); return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", _extends({ className: className, ref: this.setNode, style: newStyle }, restProps, { children: children })); } } AspectRatio.defaultProps = { className: DEFAULT_CLASS_NAME, ratio: 1 }; var _default = exports.default = AspectRatio;