react-data-grid

Dynamically adding rows to React-data-grid


I just started exploring React-data-grid and I noticed you must set the rowCount, which made me wonder if dynamically adding more rows was possible. I'm using websockets to get data which will be added as rows to the table. This could be a deal killer if it's not supported.


Solution

  • It's available to add rows dynamically. Let's assume that you're keeping the content in the state:

    this.state = {
        rows: this.props.content,
    };
    

    Also that you have a function that gets new content from the server and updates state:

    getNewData() {
        const newData = this.props.someMagicFunction();
        this.setState(prevState => ({rows: [...prevState.rows, ...newData]}));
    }
    

    rowsCount isn't a problem because you can read it as this.state.rows.length, so when you're updating your rows in the state, you're getting updated rowsCount.

    Renderer:

    <ReactDataGrid
        columns={this.props.heads}
        rowGetter={this.rowGetter}
        rowsCount={this.state.rows.length}
    />