I'm trying to add a button that toggles sorting in the grid, when I click on the button, and console log the defaultColumnDefs that sortable got toggled but the grid never rendered.
import React, { useState } from 'react';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
function App() {
const [sort, setSort] = useState(false);
const [rowData] = useState([
{ make: 'Toyota', model: 'Celica', price: 35000 },
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxter', price: 72000 },
]);
const [columnDefs] = useState([
{ field: 'make' },
{ field: 'model' },
{ field: 'price' },
]);
const [defaultColDef, setDefaultColDef] = useState({
sortable: sort,
});
const sortHandler = () => {
setDefaultColDef({ ...defaultColDef, sortable: !sort });
setSort(prev => !prev);
};
console.log(defaultColDef);
return (
<div>
<div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
<AgGridReact
columnDefs={columnDefs}
defaultColDef={defaultColDef}
rowData={rowData}
></AgGridReact>
</div>
<button onClick={sortHandler}> {sort ? 'No sort' : 'Sort'} </button>
</div>
);
}
export default App;
What might be wrong?
The sort property is stateful meaning that you can change them without having to update the column definition. To do this, you call the columnApi method applyColumnState()
See documentation on Column State
Here is an example that dynamically changes the sorting of the grid