Auto fit columns in React Treegrid component

27 Jan 20234 minutes to read

The autoFitColumns method resizes the column to fit the widest cell’s content without wrapping. You can autofit a specific column at initial rendering by invoking the autoFitColumns method in dataBound event.

import { ColumnDirective, ColumnsDirective, Inject, Resize, TreeGridComponent } from '@syncfusion/ej2-react-treegrid';
import * as React from 'react';
import { sampleData } from './datasource';
function App() {
    let treegrid;
    const dataBound = () => {
        if (treegrid) {
            treegrid.autoFitColumns(['taskName']);
        }
    };
    return <TreeGridComponent dataSource={sampleData} treeColumnIndex={1} childMapping='subtasks' height='315' allowResizing={true} dataBound={dataBound} ref={g => treegrid = g}>
            <ColumnsDirective>
              <ColumnDirective field='taskID' headerText='Task ID' width='90' textAlign='Right'/>
              <ColumnDirective field='taskName' headerText='Task Name' width='60'/>
              <ColumnDirective field='startDate' headerText='Start Date' width='120' format='yMd' textAlign='Right' type='date'/>
              <ColumnDirective field='duration' headerText='Duration' width='120' textAlign='Right'/>
              <ColumnDirective field='progress' headerText='Progress' width='120' textAlign='Right'/>
            </ColumnsDirective>
            <Inject services={[Resize]}/>
        </TreeGridComponent>;
}
;
export default App;
import { ColumnDirective, ColumnsDirective, Inject, Resize, TreeGrid, TreeGridComponent } from '@syncfusion/ej2-react-treegrid';
import * as React from 'react';
import { sampleData } from './datasource';

function App() {

    let treegrid: TreeGridComponent | null;
    const dataBound = () =>{
        if (treegrid) {
            treegrid.autoFitColumns(['taskName']);
        }
    }
        return <TreeGridComponent dataSource={sampleData} treeColumnIndex={1} childMapping='subtasks'
            height='315' allowResizing={true} dataBound= { dataBound }
            ref={g => treegrid = g}>
            <ColumnsDirective>
              <ColumnDirective field='taskID' headerText='Task ID' width='90' textAlign='Right'/>
              <ColumnDirective field='taskName' headerText='Task Name' width='60'/>
              <ColumnDirective field='startDate' headerText='Start Date' width='120' format='yMd' textAlign='Right' type='date'/>
              <ColumnDirective field='duration' headerText='Duration' width='120' textAlign='Right'/>
              <ColumnDirective field='progress' headerText='Progress' width='120' textAlign='Right'/>
            </ColumnsDirective>
            <Inject services={[Resize]}/>
        </TreeGridComponent>
};
export default App;

You can autofit all columns, by invoking autoFitColumns method without column name.