Ayman Patel
Ayman Patel

Reputation: 634

Autoresizing on load in AgGrid React

I am following the tutorial here

We have a redux application which populates the Ag-Grid when the server API is called. In the example it gives autoSizeAll as an explicit button. Is there a way to have autoResizeAll inside onGridReady.

I tried to do that but gridColumnApi is comming as null inside onGridReady

const onGridReady = (params) => {
        setGridApi(params.api)
        setGridColumnApi(params.columnApi)
     
        var allColumnIds = []
        gridColumnApi.getAllColumns().forEach(function (column) {
            allColumnIds.push(column.colId)
        })
        gridColumnApi.autoSizeColumns(allColumnIds, false) //skipHeader
    }

Upvotes: 1

Views: 349

Answers (1)

Anton Dikarev
Anton Dikarev

Reputation: 335

Resizing Columns When Data Is Rendered There are two main scenarios where you might want to resize columns based on grid data:

  • Row Data is available at grid initialisation
  • Row Data is available after grid initialisation, typically after data has been set asynchronously via a server call

In the first case you can fire autoSizeColumns() in either the gridReady or the firstDataRendered event as the row data will have been rendered by the time the grid is ready.

In the second case however you can only reliably use firstDataRendered as the row data will be made available, and hence rendered, after the grid is ready.

In your case you need to use onFirstDataRenderer callback because data is fetched from the API.

For example:

const onGridReady = (params) => {
    setGridApi(params.api)
    setGridColumnApi(params.columnApi)
}

const onFirstDataRendered = (params) => {
    var allColumnIds = []
    gridColumnApi.getAllColumns().forEach(function (column) {
        allColumnIds.push(column.colId)
    })
    gridColumnApi.autoSizeColumns(allColumnIds, false) //skipHeader
}

Upvotes: 1

Related Questions