ytan11
ytan11

Reputation: 931

React's dynamic table would not re-render after onClick action

I have a dynamic table that does not re-render itself after changes.

  renderTableData(data) {
    this.setState({ rowData: data });
    const temp = this.state.rowData.map((row, index) => {
      return (
        <tr key={row.Dono}>
          // some codes here
          <td><button onClick={e => {
            let rowData = [...this.state.rowData];
            let data = { ...rowData[index] };
            // ignore the weird 'TRUE' & 'FALSE'
            if (this.state.rowData[index].DateReceived == 'null' || this.state.rowData[index].StockReceived == 'TRUE') {
              data.DateReceived = 'null';
              data.StockReceived = 'FALSE';
            } else {
              data.StockReceived = 'TRUE';
            }
            rowData[index] = data;
            this.setState({ rowData: rowData });
          }} >{this.state.rowData[index].StockReceived}</button></td>
        </tr>
      )
    });
    this.setState({ tableData: temp });
  }

The button should display the correct value of this.state.rowData[index].StockReceived after the onClick event. However, it remains at its initial state.

Calling the renderTableData function again in the onClick event did not re-render the table, but calling the function outside the renderTableData do.

I suspect it has something to do with shouldComponentUpdate, but I am not sure.

CodeSandbox: https://codesandbox.io/s/jovial-yalow-vsk09

Note: The button in CodeSandbox requires two clicks to render its previous state, different from the browser which does no re-render at all.

Upvotes: 1

Views: 377

Answers (1)

Robert Cooper
Robert Cooper

Reputation: 2250

You shouldn't be trying to keep your JSX markup in your local state. Here is a working example: https://codesandbox.io/s/stack-overflow-data-table-ifnrn

Upvotes: 2

Related Questions