Created
October 23, 2017 07:57
-
-
Save masahirompp/eeaa179f9479a7199a4571b5814cc9a0 to your computer and use it in GitHub Desktop.
React Component, get clientWidth
This file contains hidden or 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 * 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