Lukáš Unzeitig Lukáš Unzeitig - 2 months ago 19
React JSX Question

Calll states, and class methods inside Object.keys().map in render

How i can call function and states inside the loop in render -

render(){
return(
<div
{Object.keys(this.state.valueList).map(function (item) {
return(
<Input key={item} list={this.state.disableList} x={this.getPosition(item)} />
)


})}
</div>
}

getPosition(value){
.......
}


Still getting error


TypeError: Cannot read property 'getPosition' of undefined


same with
this.state.disableList

leo leo
Answer

In your case this is not bound and accessible, so to ensure this is bound to your component and you can call your function, either use arrow functions, or bind this.

I prefer arrow functions, like this

<Input key={item} list={this.state.disableList} x={(() => this.getPosition)(item)} />

As mentioned by @Alexander T in the comments, here is how you bind this to an iterator (map, forEach, etc...)

Object.keys(this.state.valueList).map(function (item) { .... }, this)