Initial render has window size
robhadfield opened this issue · comments
On initial render I am getting the window size - if I resize the window I then get the component size but the initial values are wrong.
Any ideas?
Cheers
Rob
Actually - I'm using Webpack to render styles in dev mode - I wonder if this lag is causing the mis-calculation? I'll test and report back.
Yep - that was it. Leaving this here in case anyone has the same issue :)
So just to clarify - I'm using style-loader to load styles in the cache in dev mode - as these are loaded by Webpack on the fly there is a delay on first load and dimensions can measure before the styles ahve styled the div/component.
@robhadfield thanks for pointing this out. Do you know a fix for it without turning off style-loader?
@l85m - I'm afraid I don't have a fix. I guess you could put a timeout on the component or fire a window.resize event?
Here's a quick fix for anyone else with this issue:
SizedContainer.js
import React from 'react';
import Dimensions from 'react-dimensions';
import fireWindowResize from '../../utils/fireWindowResize'
class SizedContainer extends React.Component {
componentDidMount() {
// get component size when webpack is in dev mode
// see https://github.com/digidem/react-dimensions/issues/58
fireWindowResize()
}
render() {
const { containerHeight, containerWidth } = this.props
return(
<div height={containerHeight} width={containerWidth}>
{/* render things */}
</div>
)
}
}
export default Dimensions()(SizedContainer)
fireWindowResize.js
//http://stackoverflow.com/a/31899998/834788
export default function fireWindowResize() {
var evt = window.document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(evt);
}
Just what I was thinking! :)