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

Rex Ye
1 min readMar 15, 2021

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 anuseEffect 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…

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Rex Ye
Rex Ye

Written by Rex Ye

.net, Angular, React. Creator of epicerp.app

No responses yet

Write a response