I am using SPFx to create web part. I am generating checkboxes dynamically with map function. below is render method code
public render(): React.ReactElement<IQuickSurveyProps> {
let styles: ICheckboxStyles = {
root: {
marginTop: '10px'
}
};
let choicesArray: string[] = [];
let controlType: string = "";
return (
<div className="">
<div className="">
{this.state.isError && <div><h3>Please give proper list name</h3></div>}
{!this.state.isError &&
<div>
{
this.state.listData.map(function (e, i) {
if (e.Question_x0020_Type == "Choice") {
controlType = "Radio";
}
else if (e.Question_x0020_Type == "Checkbox") {
controlType = "Checkbox";
}
if (e.Options.indexOf(";") > 0) {
choicesArray = e.Options.split(";");
}
else if (e.Options.indexOf("\n") > 0) {
choicesArray = e.Options.split("\n");
}
return (
<div>
{e.Title}
{
(choicesArray).map(function (item, key) {
return (
<div>
{(item.length != 0) ?
(<div><input type={controlType}
name="chkbox"
value={item} />
<span>{item}</span></div>) : ""
}
</div>
)
})
}
</div>
)
})
}
<div><button id="AlertMe" type="submit" onClick={this.submitDataToSP} >AlertMe</button></div>
</div>
}
</div>
</div>
)
}
Now i want to attach click event for the the checkboxes which are generating inside map function. How I can do that? If i give like
<input type={controlType} name="chkbox"
value={item} onClick={this.checkBoxClicked} />
is giving error as checkBoxClicked is undefined even though i have defined that method. But if I try to render any checkbox out of the map function and if i try to attach an event it is working fine similar to a button AlertMe
<input type={controlType} name="chkbox" value={item} onClick={this.checkBoxClicked.bind(this, key)} />?.bind(this)would have to be chained to the function definition; that's ES5 coding. In ES6 you can use arrow functions (as Waldek answers) this does the scope binding for you.this: 2ality.com/2017/12/alternate-this.html