Search results

Autofit Columns in React TreeGrid component

29 Nov 2022 / 1 minute 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.

Source
Preview
App.jsx
App.tsx
Copied to clipboard
import { ColumnDirective, ColumnsDirective, Inject, Resize, TreeGridComponent } from '@syncfusion/ej2-react-treegrid';
import * as React from 'react';
import './App.css';
import { sampleData } from './datasource';
function App() {
    let treegrid;
    const dataBound = () => {
        if (treegrid) {
            treegrid.current.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;
Copied to clipboard
import { ColumnDirective, ColumnsDirective, Inject, Resize, TreeGrid, TreeGridComponent } from '@syncfusion/ej2-react-treegrid';
import * as React from 'react';
import './App.css';
import { sampleData } from './datasource';

function App() {

    let treegrid: TreeGridComponent | null;
    const dataBound = () =>{
        if (treegrid) {
            (treegrid.current as any).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.