UNPKG

lucid-ui

Version:

A UI component library from AppNexus.

62 lines (61 loc) 2.24 kB
import _ from 'lodash'; import React from 'react'; import PropTypes from 'react-peek/prop-types'; import { lucidClassNames } from '../../util/style-helpers'; import { omitProps } from '../../util/component-types'; import elementResizeDetectorMaker from 'element-resize-detector'; const cx = lucidClassNames.bind('&-Resizer'); const { func, string } = PropTypes; class Resizer extends React.Component { constructor() { super(...arguments); this._element = React.createRef(); this.resizeDetector = elementResizeDetectorMaker({ strategy: 'scroll' }); this.state = { width: 0, height: 0, }; this.handleResize = ({ offsetWidth, offsetHeight, }) => { this.setState({ width: offsetWidth, height: offsetHeight, }); }; } componentDidMount() { if (this._element.current) { this.resizeDetector.listenTo(this._element.current, this.handleResize); } } componentWillUnmount() { if (this._element.current) { this.resizeDetector.removeListener(this._element.current, this.handleResize); } } render() { const { className, children, ...passThroughs } = this.props; const { width, height } = this.state; return (React.createElement("div", Object.assign({}, omitProps(passThroughs, undefined, _.keys(Resizer.propTypes)), { className: cx('&', className), ref: this._element }), children && children(width, height))); } } Resizer.displayName = 'Resizer'; Resizer.peek = { description: ` This is a helper component used for getting the width and height of a containing element. This component doesn't take normal children. It expects you to pass a single function for children. It will then call that function with new \`width\` and \`height\` values if the container size changes. `, categories: ['utility'], }; Resizer.propTypes = { className: string ` Appended to the component-specific class names set on the root elements. `, children: func ` A function that returns your rendered content with the signature: \`(width, height) => {}\` `, }; export default Resizer;