Option 1
If you want to sort the columns in the sidebar only, use the handler onGridReady()
and the api argument to apply a Custom Column Layout:
<AgGridReact
onGridReady={({api}) => {
const columnsToolPanel = api.getToolPanelInstance("columns");
const sortedColumnDefs = [...columnDefs].sort((cd1, cd2) => {
if (cd1.field < cd2.field) return -1;
if (cd1.field > cd2.field) return 1;
return 0;
});
// set custom Columns Tool Panel layout
columnsToolPanel.setColumnLayout(sortedColumnDefs);
}}
//...other props
/>
Option 2
If you want to sort the columns in the table and the sidebar - it's a bit simpler - sort the column defs first, then pass it into the component:
const sortedColumnDefs = [...columnDefs].sort((cd1, cd2) => {
if (cd1.field < cd2.field) return -1;
if (cd1.field > cd2.field) return 1;
return 0;
});
return (
<AgGridReact
columnDefs={sortedColumnDefs}
// ...other props
/>
);
--EDIT--
Option 3
If you want to display the columns in the sidebar like so:
- Visible columns in default order
- Hidden columns in alphabetical order
Solution is a bit more complex, use the onColumnVisible()
handler and its columnApi
argument to access a list of the columns. Separate visible from hidden using key visible
, and sort accordingly.
<AgGridReact
onColumnVisible={({ api, columnApi }) => {
const columnsToolPanel = api.getToolPanelInstance("columns");
const columns = columnApi.getAllColumns();
const visibleColumns = columns.filter(
({ visible }) => visible === true
);
const hiddenColumns = columns.filter(
({ visible }) => visible === false
);
const sortedHiddenColumns = [...hiddenColumns].sort(
(cd1, cd2) => {
if (cd1.colDef.field < cd2.colDef.field) return -1;
if (cd1.colDef.field > cd2.colDef.field) return 1;
return 0;
}
);
const newColumns = [...visibleColumns, ...sortedHiddenColumns];
const newColDefs = newColumns.map(({ colDef }) => colDef);
columnsToolPanel.setColumnLayout(newColDefs);
}}
// ...other props
/>
Live Demo