3

In React agGrid hide: true in dynamically generated column definition is not working. My code snippet as below:

if(data.length > 0) {
  for (var key in data[0]) {
      var obj = {}
      obj.headerName = key;
      obj.field = key;
      if(obj.field == "action") {
          obj.hide = true;
          obj.suppressToolPanel = true;
      }
      cols.push(obj);
  }
}

root.setState({
  columnDefs: cols,
  rowData : data
}, function(){
  console.log(root.state.columnDefs)
});

And my agGrid in render function is as below:

<AgGridReact
  columnDefs={this.state.columnDefs}
  rowData={this.state.rowData}
  context={this.state.context}
  modules={this.state.modules}
  sideBar={this.state.sideBar}
  defaultColDef={this.state.defaultColDef}
  frameworkComponents={this.state.frameworkComponents}
  onGridSizeChanged={this.onGridSizeChanged.bind(this)}
  onCellClicked={this.onCellClicked.bind(this)}
  onFirstDataRendered={this.onFirstDataRendered.bind(this)}
  onGridReady={this.onGridReady.bind(this)}
>
</AgGridReact>

Am I missing something? Any help will be very much helpful for me.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
KOUSIK MANDAL
  • 2,002
  • 1
  • 21
  • 46

1 Answers1

0

The right way to update the column state is to use ColumnApi.setColumnState()

Also note that:

  • AgGrid version < 24: use ColumnApi.setColumnState()
  • AgGrid version >= 24: use ColumnApi.applyColumnState()
const columnState = columnApi.getColumnState() || [];

columnApi.setColumnState(
  columnState.map((c) => {
    if (Math.random() > 0.5) {
      return { ...c, hide: true };
    }
    return { ...c, hide: false };
  })
);

Live Demo

Edit gallant-hooks-w8f9y

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
  • But I want the table to be displayed with few columns hidden by default, not after some button click. – KOUSIK MANDAL Oct 29 '20 at 09:02
  • @KOUSIKMANDAL put the code in the `onGridReady` callback. My live demo has already covered that, the button is only there to demonstrate how you can update the column state programmatically. – NearHuscarl Oct 29 '20 at 10:08