Making use of the key attribute in React JS

1.5k views Asked by At

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

2

There are 2 answers

1
andy mccullough On

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.

0
Fahad Shinwari On

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'));
  }