Search code examples
reactjsmaterial-uimaterial-table

React Material Table - New field when add row


In the Material Table below taken from the example, how would I do to make the 'ahiddenfield' appear when adding a new row? I'm not really sure how to access the state when the new row is about to be added (Before onRowAdd). Is it possible without too much headache?

  constructor(props) {
    super(props);
    this.state = {
      columns: [
        { title: 'Name', field: 'name' },
        { title: 'Hidden Field', field: 'hiddenfield', hidden: true }
      ],
      data: [
        { name: 'Mehmet' },
        { name: 'Zerya Betül'},
      ]
    }
  }

  render() {
    return (
      <MaterialTable
        title="Editable Preview"
        columns={this.state.columns}
        data={this.state.data}
        editable={{
          onRowAdd: newData =>
            new Promise((resolve, reject) => {
              setTimeout(() => {
                {
                  const data = this.state.data;
                  data.push(newData);
                  this.setState({ data }, () => resolve());
                }
                resolve()
              }, 1000)
            }),
          onRowUpdate: (newData, oldData) =>
            new Promise((resolve, reject) => {
              setTimeout(() => {
                {
                  const data = this.state.data;
                  const index = data.indexOf(oldData);
                  data[index] = newData;
                  this.setState({ data }, () => resolve());
                }
                resolve()
              }, 1000)
            }),
          onRowDelete: oldData =>
            new Promise((resolve, reject) => {
              setTimeout(() => {
                {
                  let data = this.state.data;
                  const index = data.indexOf(oldData);
                  data.splice(index, 1);
                  this.setState({ data }, () => resolve());
                }
                resolve()
              }, 1000)
            }),
        }}
      />
    )
  }
} ```

Solution

  • In your <MaterialTable /> component, you should replace the data prop like this:

    data={Array.from(this.state.data)}.

    This is not documented in the docs. More info here: https://github.com/mbrn/material-table/issues/1900