skip to Main Content

I am trying to automatically resize my columns to fit their contents using an autoSizeAll function I wrote. I want this to happen every time the grid’s data is done rendering. This is because the user can click a ‘get data’ button that re-populates the grid with different data at any point in time.

My autoSizeAll function works on its own, but I am having an issue of calling it too early (before the data is done rendering), resulting in weird/no column autosizing.

Someone was able to help me get it to work by using setTimeout with an arbitrary time, but this seems like a solution that isn’t completely reliable:

useEffect(() => {
  if (rowData && rowData.length > 0) {
    setTimeout(() => autosizeAll(), 250)
  }
}, [columnDefs, rowData, autoSizeAll])

So the question is: Is there a way I can reliably check if the grid has rendered its data? AG-Grid’s firstDataRendered event works perfectly for the first render but doesn’t trigger after that. I have also tried onRowDataUpdated as well as not using the timeout, but the autosizing seems to trigger before the data is done rendering, sizing the columns in a weird way.

I would really appreciate some help! Thanks 🙂

Edit: Here is the code for autoSizeAll:

const autoSizeAll = useCallback(() => {
    const allColumnIds = [];
        gridRef.current.columnApi.getColumns().forEach((column) => {
            allColumnIds.push(column.colId);
        });
    
        gridRef.current.columnApi.autoSizeColumns(allColumnIds);

}, []);

3

Answers


  1. you can use the AG-Grid event: gridReady. The gridReady event runs once the grid is fully initialized and ready to be interacted with.
    Here is the code:

    import React, { useEffect, useRef } from 'react';
    import { AgGridReact } from 'ag-grid-react';
    import 'ag-grid-community/styles/ag-grid.css';
    import 'ag-grid-community/styles/ag-theme-alpine.css';
    
    const YourGridComponent = ({ columnDefs, rowData, autoSizeAll }) => {
      const agGridRef = useRef(null);
    
      useEffect(() => {
        if (rowData && rowData.length > 0) {
          // Resize columns after the grid is ready
          agGridRef.current.api.addEventListener('gridReady', () => {
            autoSizeAll();
          });
        }
      }, [rowData, autoSizeAll]);
    
      return (
        <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
          <AgGridReact
            ref={agGridRef}
            columnDefs={columnDefs}
            rowData={rowData}
          />
        </div>
      );
    };
    
    export default YourGridComponent;
    

    If you have any question or this doesn’t work, comment below. Hope this helps.

    Login or Signup to reply.
  2. AgGridReact have a props processRowPostCreate which takes a callback

    <AgGridReact 
        processRowPostCreate={() => {
          console.log("this is called after the table is rendered ===>")
        }} 
        rowData={rowData} 
        columnDefs={columnDefs}
      />
    

    Can you please try calling your custom function autosizeAll from here and see if it works?
    Also definition of autosizeAll would help debug this issue more.

    If you have any questions please let me know.

    Login or Signup to reply.
  3. Trying again 🙂

    To get notified by onRowDataUpdated event, we should update our data using applyTransaction

    Put this as a prop in your AgGridReact component

    onRowDataUpdated={() => autoSizeAll()}
    

    Update your data using applyTransaction like below

      const updateItems = useCallback(() => {
        // update the first 2 items
        const itemsToUpdate = [];
        gridRef.current.api.forEachNodeAfterFilterAndSort(function (
          rowNode,
          index
        ) {
          // only do first 2
          if (index >= 2) {
            return;
          }
          const data = rowNode.data;
          data.price = Math.floor(Math.random() * 20000 + 20000);
          itemsToUpdate.push(data);
        });
        const res = gridRef.current.api.applyTransaction({ update: itemsToUpdate });
        printResult(res);
      }, []);
    

    By this way, you ensure your grid is going to be resized after you update your data

    Check this plunker: https://plnkr.co/edit/1xcD5c6IKlSTOhpo?preview

    Hit on Update Top 2, see the grid resize and start digging through 😀

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search