reactjs - Retrieve element's key in React -
in react component i've created, have inside 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 didn't specify key, react warned me so. did. specified onclick event handler:
gettracks: function (e) { console.log(e.target.key); }, in hope can <div> key attribute created. not work, (i html output e.target nothing e.target.key). how can key attribute off element i've clicked on?
the best way key attribute value set pass attribute has meaning. example, this:
const userlistitems = users.map(user => { return <userlistitem key={ user.id } id={ user.id } name={ user.name } }); or in 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, think more explicit because key purely react implementation concept, mean different id, though use unique ids key values. if want have id when reference object, pass in.
Comments
Post a Comment