Last active
March 31, 2017 20:53
-
-
Save trotzig/56d1232ff48c14514371934d72fd59dd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { addEventListener, removeEventListener } from 'consolidated-events'; | |
import React, { PureComponent } from 'react'; | |
/** | |
* HoC that injects a `contextWidth` prop to the component, equal to the | |
* available width in the current context | |
* | |
* @param {Object} Component | |
* @return {Object} a wrapped Component | |
*/ | |
export default function withContextWidth(Component) { | |
return class extends PureComponent { | |
constructor() { | |
super(); | |
const initialState = { | |
contextWidth: undefined, | |
}; | |
this.state = initialState; | |
this._handleDivRef = this._handleDivRef.bind(this); | |
this._resizeHandle = addEventListener( | |
window, | |
'resize', | |
() => this.setState(initialState), | |
{ passive: true }, | |
); | |
} | |
componentWillUnmount() { | |
removeEventListener(this._resizeHandle); | |
} | |
_handleDivRef(domElement) { | |
if (!domElement) { | |
return; | |
} | |
this.setState({ | |
contextWidth: domElement.offsetWidth, | |
}); | |
} | |
render() { | |
if (typeof this.state.contextWidth === 'undefined') { | |
// This div will live in the document for a brief moment, just long | |
// enough for it to mount. We then use it to calculate its width, and | |
// replace it immediately with the underlying component. | |
return ( | |
<div | |
style={{ flexGrow: '1' }} | |
ref={this._handleDivRef} | |
/> | |
); | |
} | |
return ( | |
<Component | |
contextWidth={this.state.contextWidth} | |
{...this.props} | |
/> | |
); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lencioni just pointed me at http://elementqueries.com/, which is basically what I'm trying to do here.