@visx/bounds
Version:
Utilities to make your life with bounding boxes better
50 lines • 1.4 kB
JavaScript
/* eslint react/no-did-mount-set-state: 0 */
import { PureComponent, createRef } from 'react';
import { jsx as _jsx } from "react/jsx-runtime";
const emptyRect = {
top: 0,
right: 0,
bottom: 0,
left: 0,
width: 0,
height: 0
};
export default function withBoundingRects(BaseComponent) {
return class WrappedComponent extends PureComponent {
static displayName = (() => `withBoundingRects(${BaseComponent.displayName || ''})`)();
constructor(props) {
super(props);
this.state = {
rect: undefined,
parentRect: undefined
};
this.nodeRef = /*#__PURE__*/createRef();
this.getRects = this.getRects.bind(this);
}
componentDidMount() {
this.node = this.nodeRef?.current || null;
this.setState(() => this.getRects());
}
getRects() {
if (!this.node) return this.state;
const {
node
} = this;
const parentNode = node.parentNode;
const rect = node.getBoundingClientRect ? node.getBoundingClientRect() : emptyRect;
const parentRect = parentNode?.getBoundingClientRect ? parentNode.getBoundingClientRect() : emptyRect;
return {
rect,
parentRect
};
}
render() {
return /*#__PURE__*/_jsx(BaseComponent, {
nodeRef: this.nodeRef,
getRects: this.getRects,
...this.state,
...this.props
});
}
};
}