Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AG Grid React: How to get the state of rows after changing the order?

After implementing the drag and drop feature on AG Grid table, I’m looking for a way to get the current state with the updated order/index of rows.
My goal is to persist the table data after changing the order, but can’t find the respective state of the current order.
I’d appreciate any help or any idea.
Sandbox demo and example code below

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: "Name",
      field: "name",
      rowDrag: true
    },
    { 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
      }
    ],
    []
  );

  return (
    <div>
      <h1 align="center">React-App</h1>
      <div>
        <div className="ag-theme-alpine" style={{ height: "700px" }}>
          <AgGridReact
            columnDefs={columnDefs}
            rowData={rowData}
            defaultColDef={defaultColDef}
            onGridReady={onGridReady}
            rowDragManaged={true}
          ></AgGridReact>
        </div>
      </div>
    </div>
  );
}

export default App;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can get the order of the rows inside the grid by iterating over them using the Grid API method forEachNode:

API for Row Nodes

const rows = [];
gridApi.forEachNodeAfterFilterAndSort((node) => rows.push(node.data));
console.log(rows);

See this implemented in the following sample.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading