How to pass map indexes to array items compose of jsx element?

I had this code where I could not pass the key index of the array item map.

arrayItem = [function1, function2, function3]

<div>
   {arrayItem.map((item, index) => (<Box key={index}>{item}</Box>}
</div>

ex. for function1

const function1 = (index) => { <div> <h1> test</h1> <Button onClick((index) => console.log(index,"array number")}

It seems that I could not retrieve the index from the map when it goes to function1. The index according the console in the map is numeric but when it goes to the function, it is a className {}. The purpose of this is to retrieve the number of the array so that I could put the button delete and delete the specific array according to the index. Btw, the arrayItems is not static, so it can have more than one functions.

Thanks for the help.

Answer

React keys are special and not treated as any part of props, similarly as-is with React refs. These are not exposed to the children components. If you need to pass an index` value to a child it needs to be passed as a prop.

arrayItem = [item1, item2, item3]

<div>
  {arrayItem.map((item, index) => (
    <Box
      key={index}
      index={index} // <-- pass as a valid prop
    >
      {item}
    </Box>
  )}
</div>

Seems you are wanting to receive the index as a prop, then it needs to be accessed from props.

const function1 = (props) => (
  <div>
    <h1>test</h1>
    <Button onClick(() => console.log(prop.index, "array number")
  ...
)

Now it seems that you have an array of functional components and you want to pass the index to that component. In this case you need to render it as JSX and not just as a passed function.

<div>
  {arrayItem.map((Component, index) => ( // <-- give proper PascalCased component name
    <Component
      key={index}
      index={index} // <-- pass as a valid prop
    />
  )}
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *