Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger 'resize' event on component?

I'm writing a component decorator that is able to detect when a DOM element's size is altered (by css, javascript, window resize etc).

It already works perfectly, I'm now trying to make its API easy to use, so, what's easier than this?

class Foobar extends React.Component {
  render() {
    return <div onResize={() => console.log('resized!')}>Foobar</div>;
  }
}
ReactDOM.render(resizeAware(Foobar), app);

The problem I'm facing, is that the onResize event is not being triggered when I trigger it...

These are two attempts to trigger the event:

// method 1
onResize() {
  const resizeEvent = document.createEvent('HTMLEvents');
  resizeEvent.initEvent('resize', true, true);
  console.log('triggering resize...');
  findDOMNode(this.componentNode).dispatchEvent(resizeEvent);
}

// method 2
onResize() {
    console.log('triggering resize...');
    findDOMNode(this.componentNode).dispatchEvent(new Event('resize'));
}

If I listen for the event with:

findDOMNode(this).addEventListener('resize', () => console.log('resized'));

Everything works. So it seems like the event I'm dispatching is received by the real DOM element and not by the virtual DOM.

The question now is, why the onResize callback is not called?
If there's not a solution, how would you make my decorator API available?

NB: I don't want a way to detect the resize of the component, I just need to dispatch an event to React and make it accessible with onResize

like image 897
Fez Vrasta Avatar asked Jun 12 '16 13:06

Fez Vrasta


People also ask

How do you render a component when the browser is resized?

You can listen to the resize event in componentDidMount() and then update the dimensions ( width and height ). You should remove the listener in componentWillUnmount() method.

What happens when the window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.


1 Answers

Another NPM lib to listen to resize event of a div. Check the demo

like image 132
matt Avatar answered Oct 25 '22 14:10

matt