6

I am trying to trigger a resize without actually resizing the screen as it fixes my slider.

  window.dispatchEvent(new Event('resize')); 

The code above does not work, does anybody have any other ways of triggering a resize in react?

Had to use jQuery:

jQuery(window).resize();
BennKingy
  • 1,265
  • 1
  • 18
  • 43
  • 1
    Can't you call the `.onresize` instead? –  Oct 31 '19 at 13:55
  • jQuery(window).resize(); - this worked Chris! – BennKingy Oct 31 '19 at 14:03
  • 1
    Great, but I don't think you need to use jQuery. Try `window.onresize();` instead. Also, please don't answer questions inside the question. If you're positive this isn't a duplicate of an existing question, post your answer as actual answer. (also note that this seems to be an [xy problem](http://xyproblem.info/), we should rather be fixing the slider) –  Oct 31 '19 at 14:11

2 Answers2

7

I think you take the issue in the wrong way.

You should never rely on resize during initial view.

So your slider code have an issue on sizing which is typical when dealing with images (read the width before the image is loaded).

But if you still want to try that way

It may be depends on where do you dispatch this event ? If you dispatch it before your Slider is renderered it will not work.

A solution could be to use React.useEffect:

function MySlider() {
  React.useEffect(() => {
    // dispatch it once mounted
    window.dispatchEvent(new Event('resize')); 
  }, []);
  return <div>Your stuff</div>
}
toutpt
  • 5,145
  • 5
  • 38
  • 45
3

Stuck into the same problem for OpenLayer Map as well as D3 charts. Problem is Component didn't get mount when you dispatch that Window Resize Event. Workaround is to introduce delay while firing the event.

setTimeout(
()=>{window.dispatchEvent(new Event('resize'));},
2500
);

It should work.

u tyagi
  • 732
  • 9
  • 18