Kevin Han Kevin Han - 3 months ago 9
Javascript Question

Why can't I pass this function to onMouseEnter in React?

I think the answer is related to the context of 'this'. I am getting an error of 'cannot read props of undefined' when trying to render the createTrack by passing it the handleEnter() function. I can however, pass it a regular function without 'this' such as song.play();

Can someone give a better explanation?

handleEnter(){
this.song.play();
// this.props.mouseEnter();
}
createTrack(track){
var song = new Audio([track.preview_url]);


return (
<div className="image" key={track.id}>
<img className="img-circle" src={track.album.images[0].url} onMouseEnter={this.handleEnter.bind(this)} onMouseLeave={()=>song.pause()}/>
<p className="showMe"><span>{track.name}</span></p>
<p className="showMeArtist"><span>{track.artists[0].name}</span></p>

</div>
);
}
getTracks(){
if(this.props.tracks){
console.log(this.props.tracks);
return <div>{this.props.tracks.map(this.createTrack)}</div>
}
}
render(){
return(
<div>{this.getTracks()}</div>
)
}

Answer

I this this is the issue. add bind to the function parameter of map. Like this:

return <div>{this.props.tracks.map(this.createTrack, this)}</div>

Edit: I've changed my answer a bit. When map calls createTrack this is undefined unless you give it a thisArg param. Without thisArg map doesn't have the scope of which the function was written in. Here is the explanation from MDN -

If a thisArg parameter is provided to map, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.