Ag-Grid is a powerful data table library with tons of features. It requires some learning and doc reading, but I think it is worth it.
This post will share an Ag-Grid wrapper component that will resize columns sizes to fit its container's width automatically. If its container size changes, it will resize the columns to fit the new width.
The trick is straightforward, it watches its container's width, and window.resize
event and call sizeColumnsToFit
from AgGrid's API within an useEffect
hook.
The component props of this component extend AgGridReactProps
so we can use it the same way as we use the official AgGridReact
component.
-
useDebounce
hook from usehooks.com to reduce unnecessary calls tosizeColumnsToFit
. It is entirely optional.
-
useWindowSize
hook subscribes towindow.resize
event and update statesize
-
useContainerWidth
hook report width size withgetBoundingClientRect
API to report the element's width.
-
Finally, we have
AgGridAutoResizeToContainer
using the above hooks anduseEffect
.
The working sample is on CodeSandbox:
Happy codingโฆ
Top comments (0)