0
votes

I am using react-data-components to render a table. Inside the table I render a delete button. However, in the render method, it has no access to 'this' keyword and thus can't access any handler function on button click. I know how to communicate between parent and child components, but this doesn't seem to fall into that category. The code compiles but fails at run time. The error is: Uncaught TypeError: Cannot read property 'handleClick' of undefined Any help is appreciated.

Here's my code:

interface MyComponentProps extends RouteComponentProps {

appState: AppState;

}

@inject('appState')

class MyComponent extends React.Component {

constructor(props: MyComponentProps, context: object) {
    super(props, context);
}

renderLink(val: any, row: any) {
    console.log(this); //'this' is undefined
    return (
        <button onClick={this.handleClick}>Delete</button>
    );
}

handleClick() {
    console.log('click');
    // access appState here
}

render() {
    var columns =
        [
            { title: '', prop: 'Id', render: this.renderLink },
            { title: 'Name', prop: 'Name' }
        ];

    let data = [];
    // code to populate data

    return (<DataTable keys="fileId" columns={columns} initialData={data} />);
}

}

export default MyComponent;

1

1 Answers

0
votes

You have 2 options here.

1.- Call the handleClick as a arrow function, to bind the function.

onClick={() => this.handleClick()}

or 2.- Bind the function in the constructor:

constructor(props: MyComponentProps, context: object) {
    super(props, context);
    this.handleClick = this.handleClick.bind(this);
}

The decision is yours, I use the 2nd when is a function called multiple times, and the first one when is a one-time function.