Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions packages/react-core/src/helpers/resizeObserver.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,22 @@ import { canUseDOM } from './util';
* );
* }
*
* Example 3 - With debounced method passed in:
*
* public componentDidMount() {
* this.observer = getResizeObserver(this.inputRef.current, debounce(this.handleResize, 250), false);
* }
Comment on lines +61 to +63
Copy link
Member

@dlabrecq dlabrecq Sep 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking we can simplify the examples?

There are currently 4 full examples, but the only change seems to be in componentDidMount, so perhaps we can just show how that method? For example, something more like this might be enough:

Example 3 - With debounced method passed in

public componentDidMount() {
  this.observer = getResizeObserver(this.inputRef.current, debounce(this.handleResize, 250), false);
}

*
* @param {Element} containerRefElement The container reference to observe
* @param {Function} handleResize The function to call for resize events
* @param {boolean} useRequestAnimationFrame Whether to pass the handleResize function as a callback to requestAnimationFrame. Pass in false when the function passed in is debounced. Defaults to true.
* @return {Function} The function used to unobserve resize events
*/
export const getResizeObserver = (containerRefElement: Element, handleResize: () => void) => {
export const getResizeObserver = (
containerRefElement: Element,
handleResize: () => void,
useRequestAnimationFrame: boolean = true
) => {
let unobserve: any;

if (canUseDOM) {
Expand All @@ -69,11 +80,18 @@ export const getResizeObserver = (containerRefElement: Element, handleResize: ()
if (containerRefElement && ResizeObserver) {
const resizeObserver = new ResizeObserver((entries: any) => {
// Wrap resize function in requestAnimationFrame to avoid "ResizeObserver loop limit exceeded" errors
window.requestAnimationFrame(() => {
if (useRequestAnimationFrame) {
window.requestAnimationFrame(() => {
if (Array.isArray(entries) && entries.length > 0) {
handleResize();
}
});
// Avoid wrapping function in requestAnimationFrame if the function is debounced
} else {
if (Array.isArray(entries) && entries.length > 0) {
handleResize();
}
});
}
});
resizeObserver.observe(containerRefElement);
unobserve = () => resizeObserver.unobserve(containerRefElement);
Expand Down