Created
March 9, 2023 09:40
-
-
Save vladimir-ivanov/861df74450ab5f1f6fdd7ed462d45556 to your computer and use it in GitHub Desktop.
ag grid autoresize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useLayoutEffect } from 'react'; | |
import { debounce } from 'lodash'; | |
import { GridApi } from 'ag-grid-community'; | |
const events = [ | |
'firstDataRendered', | |
'gridSizeChanged', | |
'modelUpdated', | |
'viewportChanged', | |
]; | |
const resizeRows = debounce(() => { | |
if (!document) { | |
return; | |
} | |
const bodyViewportEl = document | |
.getElementsByClassName('ag-body-viewport') | |
.item(0); | |
const centerColContainerEl = document | |
.getElementsByClassName('ag-center-cols-container') | |
.item(0); | |
if (!bodyViewportEl || !centerColContainerEl) { | |
return; | |
} | |
const { width: centerColWidth } = | |
centerColContainerEl.getBoundingClientRect(); | |
const { width: bodyColWidth } = bodyViewportEl.getBoundingClientRect(); | |
const width = Math.max(centerColWidth, bodyColWidth); | |
Array.from(document.getElementsByClassName('ag-row')).forEach(element => { | |
const currentStyles = element.getAttribute('style')!; | |
const currentStylesArray = currentStyles | |
.split(';') | |
.map(style => style.trim()) | |
.filter(style => style !== ''); | |
const updatedStylesArray = currentStylesArray.some(style => | |
style.includes('width'), | |
) | |
? currentStylesArray.map(style => { | |
const [property] = style.split(':'); | |
if (property === 'width') { | |
return `width: ${width}px`; | |
} | |
return style; | |
}) | |
: [...currentStylesArray, `width: ${width}px`]; | |
const updatedStyles = updatedStylesArray.map(style => `${style};`).join(''); | |
element.setAttribute('style', updatedStyles); | |
}); | |
}, 100); | |
/** | |
* Hack dealing with bug in ag grid resizing | |
*/ | |
export const useGridRowsAutoResize = (gridApi?: GridApi) => { | |
useLayoutEffect(() => { | |
if (gridApi) { | |
events.forEach(event => { | |
gridApi.addEventListener(event, resizeRows); | |
}); | |
resizeRows(); | |
} | |
return () => { | |
resizeRows.cancel(); | |
if (gridApi) { | |
events.forEach(event => { | |
gridApi.removeEventListener(event, resizeRows); | |
}); | |
} | |
}; | |
}, [gridApi]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment