Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve element's key in React

Tags:

reactjs

In a React component I've created, I have this inside the render method return value:

this.props.albums.map(function(albumDetails, id) {
    return (<div className="artistDetail" key={id} onClick={component.getTracks}>
        <img src={albumDetails.imageSrc} />
        <p><a href="#" >{albumDetails.name}</a></p>
    </div>)

If I didn't specify a key, React warned me to do so. So I did. I then specified onClick event handler:

getTracks: function (e) {
   console.log(e.target.key);
},

in hope I can get the <div> key attribute I created. This does not work, however (I get some HTML output for e.target but nothing for e.target.key). How can I get the key attribute off an element that I've clicked on?

like image 965
daremkd Avatar asked Feb 08 '16 23:02

daremkd


People also ask

Can you access the key prop React?

The state and props in React are always in an object format. This means that the value could be accessed from the state and props via key-value pair. To access the normal state object, you can use the key name from the object.

How do I map a key value in React?

To map through an object's value in React: Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.

How do you use the key in React?

A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used to React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists.


1 Answers

The best way to get the key attribute value that you set is to just pass it as another attribute as well that has meaning. For example, I often do this:

const userListItems = users.map(user => {
  return <UserListItem
    key={ user.id }
    id={ user.id }
    name={ user.name }
  });

or in your case:

this.props.albums.map(function(albumDetails) {
  return (<div className="artistDetail" key={albumDetails.id} data-id={ albumDetails.id } onClick={component.getTracks}>
      <img src={albumDetails.imageSrc} />
      <p><a href="#" >{albumDetails.name}</a></p>
  </div>)

It seems redundant, but I think its more explicit because key is a purely react implementation concept, which could mean something different than id, even though I almost always use unique IDs as my key values. If you want to have id when you reference the object, just pass it in.

like image 58
Nathan Hagen Avatar answered Oct 24 '22 11:10

Nathan Hagen