3

I'm trying to return the row data when a cell is clicked in ag-Grid. I have defined the following component that I pass into the cellRendererFramework shown further down.

import { ICellRendererParams } from "ag-grid-community";
import * as React from "react";
import { CellValue } from "./ClickableCell.style";

export default class ClickableCell extends React.Component<ICellRendererParams> {
    public render() {
        return (
            // this works when the clickable cell is clicked
            // but i'm trying to return this data to the component that will be rendering the grid
            <div onClick={() => console.log(this.props.data)}>
                {this.props.value}
            </div>
        );
    }
}

The following is in the component that defines the column header and row data.

const headers = [
    { headerName: "Name", field: "name", cellRendererFramework: ClickableCell },
    { headerName: "Age", field: "age" },
];

How can I go about receiving the clicked row data in this component, where the headers are defined? Thanks!

EDIT:

I've added a somewhat working version of the code: https://codesandbox.io/s/7qlvyk901

blankface
  • 5,757
  • 19
  • 67
  • 114
  • provide a link to plunk for your issue - to play around with and solve it – Paritosh Apr 16 '19 at 07:15
  • @Paritosh I've added it to the original post but the grid doesn't seem to be rendering correctly for some reason. The basic idea of what I'm trying to achieve is all there though. – blankface Apr 17 '19 at 00:20

2 Answers2

2

Why don't you use ag-grids event handlers, in this case the onCellClicked event:

    <AgGridReact
      onCellClicked={this.onCellClicked}
      columnDefs={this.props.Headers}
      rowData={this.props.Data}
    />

Any cell event will provide you with the following parameters:

  • column: Column
  • colDef: ColDef
  • value: any
Alexander Zbinden
  • 2,315
  • 1
  • 17
  • 21
0

I haven't worked with Ag-Grid, but i would raise an event in ClickableCell and make the father handle that event.

export default class ClickableCell extends React.Component<ICellRendererParams> {
    public render() {
        return (
            <div onClick={() => this.props.onEvent(this.props.data)}>
                {this.props.value}
            </div>
        );
    }
}

Then on the father component i would define the function to handle that event and save in the state for example.

handleEvent = data => {
  console.log(data);
  this.setState({ data });
};

And pass that function via props where you call that component. If it's only in that const you should pass the props as well no?

<ClickableCell data={this.state.data} value={?} onEvent={this.handleEvent)}
Vicente
  • 2,304
  • 11
  • 15