Javascript OnClick Not Firing When Assigned Inside Of Array.map
I have created a webpage that dynamically loads its content with React.js. I'm retrieving an array of objects from a REST api call, and then feeding them into a table. The issue
Solution 1:
In the dynamic part of your code: Map()
doesn't get the value of this
from the component by default, so you need to bind it:
var fMaps = maps.map(function (map) {
return (
<FMap key={map.mapID}
sTable={map.sourceT}
sField={map.sourceF}
dTable={map.destT}
dField={map.destF}
mapCount={map.mapCount}
mapCountClick={this.editMaps} />
);
}.bind(this));
If you used ES6 arrow functions, this
would be lexically inherited and you wouldn't have this issue:
var fMaps = maps.map((map) => {
return (
<FMap key={map.mapID}
sTable={map.sourceT}
sField={map.sourceF}
dTable={map.destT}
dField={map.destF}
mapCount={map.mapCount}
mapCountClick={this.editMaps} />
);
});
Considering you are likely already using Babel or some other tool for JSX transform, might be worth looking into doing ES6 transforms as well. Good way to start learning the future!
Post a Comment for "Javascript OnClick Not Firing When Assigned Inside Of Array.map"