Reputation: 1355
Is there a way to access the key
of a map created component like the one below...
data.map((data, index) =>
<li
key={ index }
onClick={ handleClick }
>{ data }</li>
)
...or is a data
attribute required to store and access the index
like in the example below
data.map((data, index) =>
<li
key={ index }
data-index={ index }
onClick={ handleClick }
>{ data }</li>
)
Upvotes: 0
Views: 244
Reputation: 371168
The key
prop is only used by React for render optimization purposes. It cannot be seen in the DOM. So if you want to be able to access the index from inside handleClick
, you'll need to get the value into the DOM somehow - like with your data-index
.
For this particular situation, another option could be to pass it into handleClick
, eg:
data.map((data, index) =>
<li
key={ index }
onClick={ e => handleClick(e, index) }
>{ data }</li>
)
Upvotes: 1