React Native – How to pass index in map function

I have a map function to create a component repetitively and dynamically. Suppose it’s like this:

renderBoxes() {
    return Array.map(data => this.myFunction(indexOfThisArray));
}

How can I pass the index of the array? So that the ‘myFunction’ function gets the index value everytime it is called.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Map provides second argument as the index of the current element and third argument as the whole array itself.

renderBoxes() {
    return Array.map((data, index, array) => this.myFunction(index));
}

Read more about Array.prototype.map

Method 2

the syntax of map is

var new_array = arr.map(function callback(currentValue, index, array) {
    // Return element for new_array
}[, thisArg])

source. You can find the index as the 2nd parameter in the callback function

Method 3

Simply pass a second arguments to your arrow function (data, index)

renderBoxes() {
    return Array.map((data, index) => this.myFunction(indexOfThisArray));
}

Signaure for .map
var new_array = arr.map(function callback(currentValue, index, array) {
    // Return element for new_array
}[, thisArg])


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x