TheStrangeQuark
TheStrangeQuark

Reputation: 2405

Setting columnTypes in ag-grid

I'm trying to figure out how to get ag-grid working with Typescript React. I'm trying to make a table with a custom column type. The custom column type and the default column type I'm defining don't seem to be working and I'm not sure why. Here's a simple version of my code:

import React from 'react';
import './App.css';
import { AgGridReact } from 'ag-grid-react';
import { GridOptions } from "ag-grid-community";
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-balham.css';


class App extends React.Component<{}, GridOptions> {
  constructor(props: GridOptions) {
    super(props);

    this.state = {
      rowData: [
        {foo: 1, bar: 'abc'},
        {foo: 2, bar: 'def'},
      ],
      columnDefs: [
        {headerName: "foo", field: "foo", type: "numberColumn"}, 
        {headerName: "bar", field: "bar"},
      ],
      defaultColDef: {
        width: 150,
        editable: true,
        sortable: true,
        filter: "agTextColumnFilter"
      },
      columnTypes: {
        "numberColumn": {
          width: 20,
          filter: "agNumberColumnFilter"
        },
      },
      onCellClicked: function(event) {window.alert('a row was clicked '+ event.data)},
    }
  }

  render() {
    return (
      <div
        className="ag-theme-balham"
        style={{
        height: '1000px',
        width: '6000px' }}
      >
        <AgGridReact
          columnDefs={this.state.columnDefs}
          rowData={this.state.rowData}>
        </AgGridReact>
      </div>
    );
  }
}

export default App;

I also found that onCellClicked isn't actually doing anything, so I think I'm misunderstanding something there.

Upvotes: 0

Views: 9474

Answers (1)

Rikin
Rikin

Reputation: 5473

You are defining in your local state but you are not passing it to AgGridReact component this it has no knowledge of it.

You can destructure state properties like below:

    const {columnDefs, rowData, defaultColDef, onCellClicked, columnTypes} = this.state

And then use it and pass it like below:

    <AgGridReact
      columnDefs={columnDefs}
      rowData={rowData}
      defaultColDef={defaultColDef}
      onCellClicked={onCellClicked}
      columnTypes={columnTypes}
    >
    </AgGridReact>

Upvotes: 1

Related Questions