user12438439
user12438439

Reputation:

Accessing Component state AG Grid from a container

I have a component that renders AgGrid. I update the rowCount to the state of this component, however, I need to access this number (the state) from a container that this component is been displayed at

this is my State

class ClientOrderHistory extends Component {
  constructor(props) {
    super(props);

    this.state = {
      columnDefs: createColumnDefs(props.OrderHistoryReducer.columnDefs),
      gridAPI: null,
      displayedCount: 0
    };
  }

onGridReady, I have updated the function to count the number of rows

  onGridReady = params => {
    this.gridApi = params.api;
    this.columnApi = params.columnApi;
    this.setState({ gridAPI: params.api, columnAPI: params.columnApi });
    this.columnApi.autoSizeAllColumns();
    this.setState({displayedCount: this.gridApi.getDisplayedRowCount()});
    console.log('rowsCount', this.gridApi.getDisplayedRowCount());
  };

I can verify that it is working because I can console.log the state on componentDidUpdate and it displays the number of rows correctly in the console. I am passing this component to another container to display this grid, however, Id like to get this displayedCount state as a text output in the container.

How can I achieve this the best?

Upvotes: 0

Views: 433

Answers (1)

randomkrishna
randomkrishna

Reputation: 86

You should use onGridReady in your container and pass it as a prop to your AgGrid component. That's how I use it.

Else you can pass a callback function as a prop to your AgGrid component and call when the onGridReady is executed, on your AgGrid component:

onGridReady = params => {
  this.gridApi = params.api;
  this.columnApi = params.columnApi;
  this.setState({ gridAPI: params.api, columnAPI: params.columnApi });
  this.columnApi.autoSizeAllColumns();
  this.setState({displayedCount: this.gridApi.getDisplayedRowCount()});
  // your callback fn as prop
  if (this.props.callback) {
    this.props.callback(this.gridApi.getDisplayedRowCount());
  }
};

On your container:

callback = (rowCount) => // do stuff here

Upvotes: 5

Related Questions