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.
-
useDebouncehook from usehooks.com to reduce unnecessary calls tosizeColumnsToFit. It is entirely optional.
-
useWindowSizehook subscribes towindow.resizeevent and update statesize
-
useContainerWidthhook report width size withgetBoundingClientRectAPI to report the element's width.
-
Finally, we have
AgGridAutoResizeToContainerusing the above hooks anduseEffect.
The working sample is on CodeSandbox:
Happy coding…
Top comments (0)