Lukáš Unzeitig Lukáš Unzeitig - 1 year ago 65
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 -

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



Still getting error

TypeError: Cannot read property 'getPosition' of undefined

same with

leo leo
Answer Source

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)