fransua
fransua

Reputation: 533

React / how to access an extra argument passed in the map function?

Hello

I have recently started React, and I am struggling about intricating two map functions (probably not the best way to do the job but there is a long road still to make)

My question is : I would like to pass the first index i to the second map function ("here it is" comment in the code) but then I don't know how to access it inside the function.

  {images.map((index, i) => {
          return (
            <div className="item" key={i}>
              <img src={`./images/${myjson.images[index].name}`} alt="" />
              <div className="allBoxes">
                {myjson.images[index].palette.map((index, i) => {
                  console.log(i)
                  return (
                    <div
                      key={i}
                      className="colorBox"
                      style={{ backgroundColor: index }}
                      onClick={calculateNewList}
                    />
                  );
                },i)} // here it is __________________________
              </div>
            </div>
          );

Upvotes: 1

Views: 38

Answers (1)

Sina Farhadi
Sina Farhadi

Reputation: 785

Map functions don't need a reserved name for the arguments actually, which means that the order of the arguments you passed is important not the names!

map((element) => { /* … */ })
map((element, index) => { /* … */ })

Regarding the below example just put any name in the places you want! and for your example, you can follow this as well.

myArray.map((item, inedxWithWeirdName) => <p> My index is {inedxWithWeirdName} </p>)

So just put different names for your indexes name at different nested levels.

Upvotes: 1

Related Questions