Skip to content

Instantly share code, notes, and snippets.

@Gfast2
Created May 15, 2020 08:47
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 Gfast2/3a36bc6103a409160b4a92f109e00d5b to your computer and use it in GitHub Desktop.
Save Gfast2/3a36bc6103a409160b4a92f109e00d5b to your computer and use it in GitHub Desktop.
A Way to read a react component size with resize eventhandler
class DivSize extends React.Component {
constructor(props) {
super(props)
this.state = {
width: 0
}
this.resizeHandler = this.resizeHandler.bind(this);
}
resizeHandler() {
const width = this.divElement.clientWidth;
this.setState({ width });
}
componentDidMount() {
this.resizeHandler();
window.addEventListener('resize', this.resizeHandler);
}
componentWillUnmount(){
window.removeEventListener('resize', this.resizeHandler);
}
render() {
return (
<div
className="test"
ref={ (divElement) => { this.divElement = divElement } }
>
Size: <b>{this.state.width}px</b> but it should be 18px after the render
</div>
)
}
}
ReactDOM.render(<DivSize />, document.querySelector('#container'))
@Gfast2
Copy link
Author

Gfast2 commented May 15, 2020

// HTML Tag where it nested:
<div id="container"></div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment