UNPKG

azure-devops-ui

Version:

React components for building web UI in Azure DevOps

44 lines (43 loc) 1.66 kB
import "../../CommonImports"; import "../../Core/core.css"; import * as React from "react"; import { shimRef } from '../../Util'; /** * Measures the child component; expects exactly one child * Use with caution; improper use can cause severe layout thrashing */ export class Measure extends React.Component { constructor() { super(...arguments); this.childRef = React.createRef(); this.lastWidth = -1; this.lastHeight = -1; this.onResize = () => { const childElement = this.childRef.current; if (childElement) { const childRectangle = childElement.getBoundingClientRect(); // Anti-layout-thrashing - don't pass back up if (this.lastWidth != childRectangle.width || this.lastHeight != childRectangle.height) { this.props.onMeasure && this.props.onMeasure(childRectangle.width, childRectangle.height); this.lastWidth = childRectangle.width; this.lastHeight = childRectangle.height; } } }; } render() { const child = React.Children.only(this.props.children); this.childRef = shimRef(child); return React.cloneElement(child, Object.assign(Object.assign({}, child.props), { ref: this.childRef })); } componentDidMount() { window.addEventListener("resize", this.onResize); this.onResize(); } componentDidUpdate() { this.onResize(); } componentWillUnmount() { window.removeEventListener("resize", this.onResize); } }