0

I want to have a toggle functionality in my react-table component

my columns is set like

const columns = [
  {
    Header: 'ID',
    accessor : d => { return <Link to={"receipts/" + d.id}> {d.unique_id} </Link> },
  },
  {
    Header: 'Student',
    accessor: 'name'
  },
  {
    Header: 'Paid Amount',
    accessor: 'paid_amount',
  },
  {
    id: 'is_paid',
    Header: 'Paid?',
    accessor: d => {
      console.log(d);
      return <Form.Check id={d.id} type='switch' checked={d.is_paid} onChange={this.handleToggle.bind(this)}/>
    }
  },
];

and my handleToggle is simply making an API call to update this row

But I'm getting

TypeError: Cannot read property 'handleToggle' of undefined

It seems like I'm not getting the this in my columns. How do I access this?

JChao
  • 2,178
  • 5
  • 35
  • 65
  • https://stackoverflow.com/questions/38589227/why-this-is-undefined-inside-a-fat-arrow-function-definition – Minato Dec 17 '20 at 06:42
  • Since the fat arrow function takes the scope of the parent/grand-parent/..., and `this` is undefined there, that must mean columns is not declared inside a regular function or a global function. – Minato Dec 17 '20 at 06:45
  • I'm sorry I'm new to reactjs. What's the approach then? Should I simply remove the arrow and everything will work? – JChao Dec 17 '20 at 10:01
  • Where is `handleToggle` defined, and since you're binding `this` what do you want to use from current scope? – Minato Dec 17 '20 at 12:28

1 Answers1

-1

Have a look at this example https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/editable-data, it can be helpful in passing your own props to table and then using them in cell.

Rohit Garg
  • 782
  • 5
  • 18