skip to Main Content

I am using ag grid 27 community version in a react typescript application.I am wondering how to set the total width to something like ‘auto’. Like when there are fewer columns and on larger screens the container should occupy only that much width and not 100% width. Also on smaller screens with an overflowX auto.

I used these styles for the wrapper div

const gridStyle = useMemo(() => ({ height: '100%', width: 'auto', overflowX: 'auto' }), []);

and jsx looks like

<div style={gridStyle} className="ag-theme-alpine">
    <AgGridReact rowData={rowData} columnDefs={columnDefs} />
</div>

But no success!Tried a basic table here https://plnkr.co/edit/xKxE6OktkUR4OStF

I am trying to do is to avoid the extra vacant space to the right when the screen is large or not enough columns to show. In the case of smaller screens horizontal scroll is fine.
enter image description here

2

Answers


  1. For this scenario, AG Grid provides ‘minWidth’ and ‘maxWidth’ properties under column sizing section. I am attaching link for your reference:
    https://www.ag-grid.com/react-data-grid/column-properties/#reference-width-minWidth

    Login or Signup to reply.
  2. In your code, you use maxWidth for every columns in columnDefs. That’s why all columns’s width are not as expected.

    You can use flex: 1 in columnDefs for specific columns.

    columnDefs: [
    {
      headerName: 'SN',
      field: 'sn',
      flex: 1
    },.....
    ]

    But note that flex doesn’t work with width. You can only combine flex with maxWidh and minWidth.

    My favorite config is set flex:1 in defaultColDef to apply for all column and custom minWidth/maxWidth for each columns.

    const defaultColDef = useMemo(() => {
      return {
        wrapHeaderText: true,
        resizable: true,
        sortable: true,
        filters: true,
        flex: 1,
      };
    }, []);
    
    columnDefs: [{
        headerName: 'SN',
        field: 'sn',
        minWidth: 80,
        maxWidth: 90,
      },
      {
        headerName: 'Sub-trade',
        field: 'subTrade',
        minWidth: isHdScreen ? 70 : 90
      },
    
      .....
    ]

    This answer gave references for this.
    And remember to pass props to ag-grid

    <div style={gridStyle} className="ag-theme-alpine">
        <AgGridReact rowData={rowData} columnDefs={columnDefs} defaultColDef={defaultColDef} />
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search