Blog>
Snippets

Integrating Column Pinning with Sorting

Provide an example of how column pinning can coexist with column sorting functionalities, ensuring that the pinned column retains sorting capabilities.
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
Import AG Grid React component and its styles.
const gridOptions = {
    defaultColDef: {
        sortable: true,
        filter: true,
        resizable: true,
        pinned: null
    }
};
Define the grid options including default column definitions to make all columns sortable, filterable, and resizable. We also prepare the 'pinned' property which will allow us to pin columns.
const columnDefs = [
    { headerName: 'ID', field: 'id', pinned: 'left' },
    { headerName: 'Name', field: 'name' },
    { headerName: 'Value', field: 'value' }
];
Define the column definitions for our grid. We specify one column to be pinned to the left. Other columns remain unpinned and can be interacted with normally.
const rowData = [
    { id: 1, name: 'Product A', value: 100 },
    { id: 2, name: 'Product B', value: 200 },
    // more rows here
];
Define row data for the grid. This data will populate the cells.
const onGridReady = params => {
    params.api.sizeColumnsToFit();
};
Define a function that will be called once the grid is ready, using it to adjust the column sizes to fit the grid width.
<div className='ag-theme-alpine' style={{ height: 400, width: 600 }}>
    <AgGridReact
        gridOptions={gridOptions}
        columnDefs={columnDefs}
        rowData={rowData}
        onGridReady={onGridReady}
    />
</div>
Render the AG Grid component within a styled div element. We apply the Alpine theme for styling, passing our previously defined grid options, column definitions, and row data to the component. We also bind the onGridReady function to adjust column sizes on initial load.