Created
May 15, 2020 08:47
-
-
Save Gfast2/3a36bc6103a409160b4a92f109e00d5b to your computer and use it in GitHub Desktop.
A Way to read a react component size with resize eventhandler
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
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')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// HTML Tag where it nested:
<div id="container"></div>