Newb 4 You BB
Newb 4 You BB

Reputation: 1355

Access Key of Map Created Component

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

Answers (1)

CertainPerformance
CertainPerformance

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

Related Questions