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?
onResize
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.
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.
Another NPM lib to listen to resize event of a div. Check the demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With