Kevin Han Kevin Han - 1 year ago 73
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;

Can someone give a better explanation?

// this.props.mouseEnter();
var song = new Audio([track.preview_url]);

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

return <div>{}</div>

Answer Source

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

return <div>{, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download