Skip to content

Instantly share code, notes, and snippets.

@masahirompp
Created October 23, 2017 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masahirompp/eeaa179f9479a7199a4571b5814cc9a0 to your computer and use it in GitHub Desktop.
Save masahirompp/eeaa179f9479a7199a4571b5814cc9a0 to your computer and use it in GitHub Desktop.
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