In my react app, I have an onClick
function that isn't being recognized (TypeError: _this2.click is not a function
) when called from dynamically-generated components. I poked around for issues with functions not being bound correctly, but they seem to be. Here's the code:
class C extends React.Component {
constructor(props) {
super(props);
// Bind components
this.eventComponent = this.eventComponent.bind(this);
this.click = this.click(this);
}
/**
* Click function for when a user selects their choice
* @param {[int]} id [id of the event the user is selecting]
*/
click(id) {
console.log(id)
}
/**
* Draws an event component (dynamically generated)
* @param {[String]} name [name of the event]
* @param {[String]} summary [summary of event]
* @return {[Object]} [react element of an event]
*/
eventComponent(name, summary, id) {
if (name != null && summary != null) {
return (
<div >
<h1>{name}</h1>
<p>{summary}</p>
<button onClick={() => this.click(id)}>Here is a button!</button>
</div>
);
}
}
render() {
var event = this.state.event
var objArray = this.state.objArray
var eventMap;
if (event) {
eventMap = objArray.map(function(event) {
// Get first property
var firstProp;
var k;
for(var key in event) {
if(event.hasOwnProperty(key)) {
firstProp = event[key];
k = key;
break;
}
}
return this.eventComponent(firstProp.title, firstProp.summary, k);
}.bind(this))
} else {
eventMap = <p>No events found!</p>;
}
// Generate a default HTML object
var eventComponent = (
<div>
{eventMap}
</div>
);
return eventComponent;
}
}
this.click.bind(this);