DEV Community

Rex
Rex

Posted on

Build an Ag-Grid React Component that Auto Resize Columns To Fit Container Width

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.

  1. useDebounce hook from usehooks.com to reduce unnecessary calls to sizeColumnsToFit. It is entirely optional.

  2. useWindowSize hook subscribes to window.resize event and update state size

  3. useContainerWidth hook report width size with getBoundingClientRect API to report the element's width.

  4. Finally, we have AgGridAutoResizeToContainer using the above hooks and useEffect.

The working sample is on CodeSandbox:

Happy coding…

Top comments (0)