I am rendering 'rows' of job listings represented by li
elements created by calling map
on a prop that holds an array of job listings.
Each li
has an onClick
handler within which I need to access the id
associated with the clicked row in order to show the detail page of the job listing with that id
. Note that the map
adds the id
values of the job listings as the key
properties of the li
elements.
The map
function looks something like this:
var jobListRow = this.props.joblists.map(function(jobrowobj) {
return (
<li key={jobrowobj.id} onClick={this.handleClick}>
<div>bla bla</div>
<span>bla bla</span>
</li>
);
});
And the onClick
handler looks like this:
handleClick: function(event) {
console.log(event.target);
}
Inside the handler I hoped to use the target
of the clicked li
to get the value of the key
property for that li
, but the target
returned seems to be different every time and happens to be a varying child element of the li
. How can I access the key
of the li
that was clicked? Or, phrased differently: how can I access the id
of the job listing that was clicked?
This should work, you need to have the right context binding:
var jobListRow = this.props.joblists.map(function(jobrowobj, i){
return(
<li key={jobrowobj.id} onClick={this.handleClick.bind(this,i)}>
<div>bla bla</div>
<span>bla bla</span>
</li>
)
});
handleClick: function(i) {
console.log('You clicked: ' + this.props.joblists[i]);
}
Found this implementation here: https://facebook.github.io/react/tips/communicate-between-components.html
It seems it fits your needs. Hope it helped