react-aspect-ratio
Version:
React Component to maintain a consistent width-to-height ratio (aspect ratio), preventing cumulative layout shift.
38 lines (37 loc) • 1.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const CUSTOM_PROPERTY_NAME = '--aspect-ratio';
const DEFAULT_CLASS_NAME = 'react-aspect-ratio-placeholder';
class AspectRatio extends react_1.Component {
static defaultProps = {
className: DEFAULT_CLASS_NAME,
ratio: 1,
};
node = null;
componentDidUpdate() {
if (this.node) {
const { node } = this;
// BC for older version of React https://github.com/facebook/react/issues/6411
// check if React support custom property AFTER
const customPropertyValue = node.style.getPropertyValue(CUSTOM_PROPERTY_NAME);
if (!customPropertyValue) {
node.style.setProperty(CUSTOM_PROPERTY_NAME, `(${this.props.ratio})`);
}
}
}
setNode = (node) => {
this.node = node;
};
render() {
const { className, children, ratio, style, ...restProps } = this.props; // eslint-disable-line no-unused-vars
const newStyle = {
...style,
// https://github.com/roderickhsiao/react-aspect-ratio/commit/53ec15858ae186c41e70b8c14cc5a5b6e97cb6e3
[CUSTOM_PROPERTY_NAME]: `(${ratio})`,
};
return ((0, jsx_runtime_1.jsx)("div", { className: className, ref: this.setNode, style: newStyle, ...restProps, children: children }));
}
}
exports.default = AspectRatio;