Skip to content

Instantly share code, notes, and snippets.

@curran
Forked from AdamMcCormick/ScrollBarAdapter.jsx
Last active April 11, 2021 23:27
Show Gist options
  • Save curran/0e30c621fe4fc612bf7feb0938a68e4d to your computer and use it in GitHub Desktop.
Save curran/0e30c621fe4fc612bf7feb0938a68e4d to your computer and use it in GitHub Desktop.
A hook to listen for width changes or scroll-bar show/hide.
import { useEffect } from 'react';
/**
* A hook to listen for width changes or scroll-bar show/hide.
*
* Arguments:
* * containerRef - a React ref to the element whose width you want to measure.
* * onWidthChanged - a function that is invoked when the width changes.
*
* Based on https://gist.github.com/AdamMcCormick/d5f718d2e9569acdf7def25e8266bb2a
*/
export const useWidthDetector = (containerRef, onWidthChanged) => {
useEffect(() => {
if (containerRef) {
const detector = document.createElement('iframe');
Object.assign(detector.style, {
height: 0,
border: 0,
width: '100%'
});
const container = containerRef.current;
container.appendChild(detector);
// Invoke here to capture initial width.
onWidthChanged();
// Detect when width changes hereafter.
detector.contentWindow.addEventListener('resize', onWidthChanged);
return () => {
detector.contentWindow.removeEventListener('resize', onWidthChanged);
container.removeChild(detector);
};
}
}, [containerRef, onWidthChanged]);
};
@curran
Copy link
Author

curran commented Mar 10, 2021

Very nice!

@finnmerlett
Copy link

I cannot believe I didn't find this before. Waaaay simpler - https://github.com/maslianok/react-resize-detector

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment