0

I'm currently trying to generate a table that can not only display values as dynamic as possible, but also have functionality that gets passed to a certain column. The draft of the structure is like this:

<Table
      dataHeaders={[
        { headerTitle: 'ID', headerKey: 'id', filterable: true },
        { headerTitle: 'First Name', headerKey: 'firstname', filterable: true, sortable: true },
        { headerTitle: 'Last Name', headerKey: 'lastname', filterable: true, sortable: true },
        {
          headerTitle: 'Details',
          text: 'Show details',
          functionalColumn: true,
          function: row => {
            alert(`${row.id}: ${row.firstname} ${row.middlename} ${row.lastname}`);
          },
        },
        {
          headerTitle: 'Delete',
          text: 'Delete',
          functionalColumn: true,
          function: row => {
            const remainingData = this.state.data.filter(item => item.id !== row.id);
            this.setState({ data: remainingData });
          },
        },
      ]}
      data={[
        { id: 1, firstname: 'Jess', lastname: 'Smith' },
        { id: 2, firstname: 'Alex', lastname: 'Williams' },
        { id: 3, firstname: 'Tayler', lastname: 'Brown' },
        { id: 4, firstname: 'Hannah', lastname: 'Anderson' },
        { id: 5, firstname: 'Anna', lastname: 'Adams' },
        { id: 6, firstname: 'Michael', lastname: 'Johnson' },
        { id: 7, firstname: 'John', lastname: 'Willis' },
        { id: 8, firstname: 'Joey', lastname: 'Sullivan' },
        { id: 9, firstname: 'Chandler', lastname: 'Anderson' },
        { id: 10, firstname: 'Monica', lastname: 'Black' },
        { id: 11, firstname: 'Rachel', lastname: 'Tyson' },
        { id: 12, firstname: 'Alex', lastname: 'Doe' },
      ]}
    />

Showing the details works completely fine, using this code in the Table component:

<td key={`${metaColumn.text}-${index}`}>
   <span className={'Table__delete'} onClick={metaColumn.function.bind(this, row)}>
        {metaColumn.text}
   </span>
</td>

However, and not surprisingly, manipulating the state of Table doesn't work properly, as apparently binding the method with bind(this, row) isn't sufficient.

Is there a way I can make this.state accessible in this kind of environment?

LordAnomander
  • 1,103
  • 6
  • 16

1 Answers1

1

So, I finally figured out, why it wouldn't work. The reason is quite simple: you cannot change the context of this in arrow functions.

So instead of

function: row => {
    const remainingData = this.state.data.filter(item => item.id !== row.id);
    this.setState({ data: remainingData });
}

I used:

function(row) {
    const remainingData = this.state.data.filter(item => item.id !== row.id);
    this.setState({ data: remainingData });
}
LordAnomander
  • 1,103
  • 6
  • 16