Reputation: 1348
So I wrote a component with an event handler that is supposed to get the id of the element and it's parentNode. My code looks something like this:
class Schedule extends React.Component {
constructor(props){
super(props);
this.handleSelect = this.handleSelect.bind(this);
}
handleSelect(e){
let week = e.target.parentNode.id;
let day = e.target.id;
this.props.onSelect(week, day);
}
render(){
let schedObj = this.props.meal;
let sched = schedObj.map(weekArr => weekArr.map((dayArr, ind1) =>
<td id={ind1} className={"div"+ind1} onClick={this.handleSelect}>{dayArr.map(item => <p>{item.rName}</p>)}</td>));
return(
<div>
<table>
<tbody>
<tr id="0">
{sched[0]}
</tr>
<tr id="1">
{sched[1]}
</tr>
</tbody>
</table>
</div>
);
}
}
Ideally, e.target.id would be the id for the div, and e.target.parentNode.id would be the id for the tr. However, when I click on it, it will occaisionally give me the id of the p within the div as the e.target.id, and the for the as the e.target.parentNode.id. I'm guessing since the p is nested within the div, the handleSelect(e) event handler still applies to it. How can I get this to only work for the div and not its children?
Upvotes: 0
Views: 488
Reputation: 281894
Since you have defined an onClick on the td element, and you have a <p>
tag inside of td, need to use e.currentTarget.id
to get the id of the td
handleSelect(e){
let week = e.target.parentNode.id;
let day = e.currentTarget.id;
this.props.onSelect(week, day);
}
currentTarget
gives you the element on which the handler is defined, while target
gives you the element on which the event happened and since you have a p
inside td
it may so happen that you clicked on the <p>
tag and hence you do not get the id
of <td>
element onClick
Upvotes: 1