Understanding synthetic events in ReactJS
There's actually no magic going on here, just passing functions around. onVideoSelected
is a function reference that you passed into the Video
component via a property; said another way, the flow goes like this:
- What happens when you click the div? Call
this.handleClick
. - What happens when you call
handleClick
? Callthis.props.onVideoSelected
. - How is
onVideoSelected
defined? It got passed into the component, just like any other property. - What was passed in to the
onVideoSelected
property? A reference to theVideoList
'shandleVideoSelected
function.
It may help to compare it to some sorta-similar, simplified jQuery code:
function handleVideoSelected(title) { console.log('selected Video title is: ' + title);}function createVideoDiv(onVideoSelected, title) { var div = $("<div className="bg-success"></div>").text(title).appendTo(...); div.on("click", function() { // call the function that was passed to us onVideoSelected(title); });}$.each(videos, function(idx, video) { createVideoDiv(handleVideoSelected, video.title);});
In the jQuery version, you pass handleVideoSelected
into createVideoDiv
; similarly, in the React version, you pass handleVideoSelected
into Video
via props.
After your onClick
handler is called in the Video
component you are no longer dealing with events; these are plain old function calls.
To keep a reference to the video title, pass a curried version of handleVideoSelected
with the title as the first arg by using Function.prototype.bind:
{this.props.data.map(function (v) { return <Video onVideoSelected={this.handleVideoSelected.bind(this, v.title)} key={v.title} title={v.title} />;}, this)}
(I also prepended this.props
to data
. Looks like a typo in your code.)
This is how individual Todos are identified in the "Expose Component Functions" doc.