Null Salad
Null Salad

Reputation: 1030

React onClick event yields: "Uncaught TypeError: Cannot read property of undefined", despite binding

I'm writing a React script that will render a bunch of <a /> elements from a previously defined array.

...
render:
...
    var behaviourComponents = this.props.myObjectArray.map(function(element) {
                    return <a className="crumbFile" onClick={this._myFunction.bind(this,element.value1)}>{element.value2}</a>;
                });
    return (
...
<div>{behaviourComponents}</div>
...)

This works fine when there is no function call with onClick. However, when there is I get the error: "Uncaught TypeError: Cannot read property '_myFunction' of undefined".

This is extra strange because I have a component right before it with an onClick function call that works fine (<a class="btn header" style={buttonStyle} onClick={this._onLoad}>Load</a>), which makes me think this is a scoping issue due to the map() function. However, I used .bind(), so I am not too sure what's wrong here.

Upvotes: 1

Views: 4144

Answers (1)

Michael Parker
Michael Parker

Reputation: 12966

This is because the context inside of the function you pass to map() is not referring to your React component class. By default, the context is the global Window object.

There are a few ways to solve this issue:

1) Bind the correct context of this to the function passed to map().

this.props.myObjectArray.map(function(element) {
    ...
}.bind(this));

2) Pass the correct context as the second argument to map()

this.props.myObjectArray.map(function(element) {
    ...
}, this);

3) Use an ES6 arrow function, which will bind the correct context for you.

this.props.myObjectArray.map(element => {
    ...
});

Upvotes: 12

Related Questions