Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Component, get clientWidth
import * as React from 'react'
import { debounce } from 'lodash'
interface Props {
childrenAsFunction: (width: number) => JSX.Element
}
interface State {
width: number
}
class ClientWidth extends React.Component<Props, State> {
$el: HTMLDivElement
constructor(props: Props) {
super(props)
this.state = {
width: 0
}
}
updateWidth() {
if (!this.$el) {
return
}
const width = this.$el.clientWidth
if (this.state.width !== width) {
this.setState({ width })
}
}
componentWillMount() {
this.updateWidth = debounce(this.updateWidth.bind(this), 300).bind(this)
window.addEventListener('resize', this.updateWidth)
}
componentDidMount() {
this.updateWidth()
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWidth)
}
render() {
return (
<div
style={{ width: '100%' }}
ref={el => {
if (el) {
this.$el = el
}
}}
>
{this.props.childrenAsFunction(this.state.width)}
</div>
)
}
}
export default ClientWidth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.