'How to set new Sequence of the index while creating a new row in a table?
In the following example below, I create a new table with a custom column named label, which is, literally, the index of the gridRow array of objects.
I faced a problem while trying to create a new row which is inserted before the last element, (before last object in my case).
And there came the problem with not getting in the sequence of the label/index.
import React 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 [gridApi, setGridApi] = React.useState(null);
const [gridColumnApi, setGridColumnApi] = React.useState(null);
const onGridReady = (params) => {
setGridApi(params.api);
setGridColumnApi(params.columnApi);
};
const defaultColDef = {
flex: 1,
editable: true
};
const columnDefs = [
{
headerName: "label",
field: "label"
},
{
headerName: "Name",
field: "name"
},
{ headerName: "stop", field: "stop" },
{
headerName: "duration",
field: "duration"
}
];
const rowData = React.useMemo(
() => [
{
name: "John",
stop: 10,
duration: 5
},
{
name: "David",
stop: 15,
duration: 8
},
{
name: "Dan",
stop: 20,
duration: 6
}
],
[]
);
const rowDataWithIndex = React.useMemo(() => {
return (
rowData &&
rowData.map((row, index) => ({
...row,
label: index
}))
);
}, [rowData]);
const addNewRow = () => {
gridApi.applyTransaction({
add: [{ label: rowDataWithIndex[rowDataWithIndex.length - 2].label + 1 }],
addIndex: rowDataWithIndex.length - 1
});
};
return (
<div>
<h1 align="center">React-App</h1>
<div>
<button onClick={addNewRow}>New Row</button>
<div className="ag-theme-alpine">
<AgGridReact
columnDefs={columnDefs}
rowData={rowDataWithIndex}
defaultColDef={defaultColDef}
domLayout={"autoHeight"}
onGridReady={onGridReady}
></AgGridReact>
</div>
</div>
</div>
);
}
export default App;
Any help will be appreciated
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
