skip to Main Content

I would like to include in my grid an extra column to reflect the up to date sum of two other columns:

const columnDef = [
    {headerName: 'x', field: 'x', type: 'numericColumn'},
    {headerName: 'y', field: 'y', type: 'numericColumn'},
    {headerName: 'z', function: (data) => data.x+data.y}
];

How can I do that?

2

Answers


  1. Afaik you cannot set the value directly in the useState of your values. But you can edit the values in the useEffect after loading and insert the values you need. I set the total value to 0 by default. In the useEffect I update the values of the total field. Here is a modified example from the ag-gird documentation (https://www.ag-grid.com/react-data-grid/getting-started/)

    import React, { useState, useEffect } from 'react';
    import { AgGridReact } from 'ag-grid-react';
    
    import 'ag-grid-community/styles/ag-grid.css';
    import 'ag-grid-community/styles/ag-theme-alpine.css';
    
    export default function App() {
      const calcTotal = (count, price) => {
        return count * price;
      };
    
      const [rowData, setRowData] = useState([
        { make: 'Toyota', model: 'Celica', count: 3, price: 35000, total: 0 },
        { make: 'Ford', model: 'Mondeo', count: 3, price: 32000, total: 0 },
        { make: 'Porsche', model: 'Boxter', count: 3, price: 72000, total: 0 },
      ]);
    
      useEffect(() => {
        setRowData((prevRowData) =>
          prevRowData.map((row) => ({
            ...row,
            total: calcTotal(row.count, row.price),
          }))
        );
      }, []);
    
      const [columnDefs] = useState([
        { field: 'make' },
        { field: 'model' },
        { field: 'price' },
        { field: 'count' },
        { field: 'total' },
      ]);
    
      return (
        <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
          <AgGridReact rowData={rowData} columnDefs={columnDefs}></AgGridReact>
        </div>
      );
    }
    

    Let me know if that helps.

    Login or Signup to reply.
  2. All you need is a simple valueGetter to add the 2 values of your x and y fields.

    Change your columnDefs to:

      const [columnDefs] = useState([
          {headerName: 'x', field: 'x', type: 'numericColumn'},
          {headerName: 'y', field: 'y', type: 'numericColumn'},
          {headerName: 'z', valueGetter: function(event) {
            return event.data.x + event.data.y;
          }}
      ]);
    

    Demo.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search