Retrieve element's key in React Retrieve element's key in React reactjs reactjs

Retrieve element's key in React


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.


The key is for React's internal use and won't display in the HTML and Console, you just have to use the id to retrieve that unique component.eg:

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

And also you don't need to pass value to the key attribute.Value is completely optional.