renatorib / react-sizes

:left_right_arrow: Hoc to easily map window sizes to props.
722 stars 36 forks source link

Size props don't update when `resize` event is used in the child #43

Open aviaryan opened 5 years ago

aviaryan commented 5 years ago

React Sizes won't update the props when a child component is also using the resize event.

Example - A child component of the component that I am using withSizes on has a resize handler defined.

window.addEventListener('resize', this.resize);
// using this.resize to re-render (child) component in case window resizes

When the above is defined, react sizes fails to update the props passed to the parent component.

When I remove the resize handler from the child component and make no other changes, react-sizes works as expected. That's why I think there could be a bug here.

Let me know if you need any more details.

renatorib commented 5 years ago

Can you show me a minimal reproduction so I can take a look?

aviaryan commented 5 years ago

Thanks for the quick reply. I created a test sandbox to share here but the same doesn't seem to be happening in it. Looking into my original code, here is what is happening.

  1. window and document is at 1300px width.
  2. Using dev tools, we change the window to mobile width (<480px) instantly.
  3. resize handlers fire. The child has an absolute positioned element that takes some time to adjust to the new width because the width is based on a state value which is updated on resize. The absolute position element is initially taking 1200px width.
  4. Because the child will take some time, viewport width is still at 1200px as the absolute element is still in its original size. So the parent with withSizesHOC doesn't update isMobile prop since breakpoint is at 480px.
  5. The child finally adjusts the absolute element thus decreasing viewport width to be < 480px.
  6. resize event isn't fired now or maybe it is throttled causing withSizes to not update the isMobile prop.

If it is a bug, it could be related to #32

However, since I am not able to replicate it on the test code, you can close this issue. I am thinking of using a different approach for what I am doing anyway.

You can find the test code here. https://codesandbox.io/embed/react-sizes-issue-r706q