Search code examples
reactjsag-gridag-grid-react

Create a new row through a rendered React component


I used cellRenderer with frameworkComponents to render a button component as a column.

import InsertNodeBtnRender from "./HierarchyButtons/insertRowBtn.jsx";

columnDefs: [
        {
          lockPosition: true,
          cellRenderer: "insertBtnRender",
          // cellClass: 'locked-col',
          maxWidth: 60,
          // suppressNavigable: true,
        },
        { field: "jobTitle" },
        { field: "employmentType" },
      ],
      frameworkComponents: {
        insertBtnRender: InsertNodeBtnRender,
      },
class InsertNodeBtn extends Component {

  btnClickedHandler() {
  // I have access to "this.props.node" for setting data to EXISTING rows
  }

  render() {
    return <button onClick={() => this.btnClickedHandler()}>+</button>;
  }
}

export default InsertNodeBtn;

Within the handler in the above component, I am able to manipulate the existing row node with the props property (such as use this.props.node.setData()). However, I simply want to ADD a new row to the grid with some of the data fields based on the current cell.

Pressing the "+" button should create a new row with the same data values

How would I go about this? There doesn't seem to be provided method within the API that allows me to do this and is accessible within the component event handler. https://www.ag-grid.com/javascript-grid-data-update/#gsc.tab=0

TLDR; After pressing the "+" button. How do I add a NEW row to the grid?


Solution

  • You can use GriApi.applyTransaction({ add: newItems }) to add new rows to the grid. See update-transaction section for more info. Here is an example:

    import React from "react";
    
    let i = 0;
    
    function createNewRowData({ orgHierarchy, employmentType }) {
      const boss = orgHierarchy[orgHierarchy.length - 1];
      const newData = {
        jobTitle: "Minion",
        employmentType,
        orgHierarchy: orgHierarchy.concat(boss + "'s Minion " + ++i)
      };
      return newData;
    }
    
    export default function InsertNodeBtnRender(props) {
      const { api, columnApi, data } = props;
      const onAdd = () => {
        const newItems = [createNewRowData(data)];
    
        api.applyTransaction({ add: newItems });
        columnApi.autoSizeAllColumns();
      };
    
      return <button onClick={onAdd}>+</button>;
    }
    

    Live Demo

    Edit 63946523/ag-grid-react-create-a-new-row-through-a-rendered-react-component