0

I have an array of values coming from an API, it contains the list of values. I am mapping all these values in an array of cards (as mentioned in the code below). I need to extract the id of the selected element, it is stored in the key attribute. Is there a way to use/reference the value of the key attribute?

{data.map((item) => (
          <Card key={item[0]} element={item} />
        ))}

I am developing a KaiOS app and hence cursor interactions (onClick or onHover) are restricted. There is a nav-focus attribute (maintained using a custom hook) which is used to determine if the current element is selected and used CSS to highlight it (as shown in the image below) on that basis. I don't want to maintain a state of the selected element as it would be updated every time I navigate amongst the cards.

I would like to know if there is a way to use the key attribute of the selected item

Image from wikiHow showing a highlighted option

Aditya Priyam
  • 156
  • 1
  • 11

2 Answers2

1

I don't want to maintain a state of the selected element as it would be updated every time I navigate amongst the cards.

State is the correct way, why the want for not using state.

Keys should be used for uniquely identifying items rendered as a list, e.g. using map() and shouldn't really be used as other props would be.

andy mccullough
  • 9,070
  • 6
  • 32
  • 55
1

Use a key in the html. It will solve the problem you suggested. and it will get the selected item as an attribute by the getAttribute property.

<div>
      <select onChange = {this.onSelect}>
       <option key="1" language="english">English</option> 
       <option key="2" language="espanol">Espanol</option> 
            </select> 
</div>

Now onSelect function which will console log the selected language:

onSelect=(event)=> {
    const selectedIndex = event.target.options.selectedIndex;
    console.log(event.target.options[selectedIndex].getAttribute('language'));
  }
Fahad Shinwari
  • 968
  • 7
  • 7