Reputation: 6342
I am using react for development and for performance reason i want o capture the click a topmost parent level.
const clickHandler = (e) => {
console.log("clickHandler", e.target) --> give me the child element in which the click occurred
}
so even if the nested child i should be able to get the ID. And there are going be 1000's card and the childen structure is also complex
<div onClick={clickHandler}>
<div class="card" id="12345">
<div class="x1">
<div class="x2">
<div class="">
<span class="">
<ul class="">
</div>
</div>
<div class="card" id="67890">
<div class="x1">
<div class="x2">
<div class="">
<span class="">
<ul class="">
</div>
</div>
</div>
Upvotes: 0
Views: 29
Reputation: 6342
After some reading i found this article ,
https://dev.to/thawsitt/should-i-use-event-delegation-in-react-nl0
in which Dan Abhromov state that, there is no advantage of doing this in react. As React using Synthetic events and event is already being captured in the root element.
Upvotes: 0
Reputation: 195982
If you want to get the id
of the element with the card
class when you click anywhere inside it.
You can use .closest
to find the relevant parent you want.
Keep in mind that this is not react related, and it also seems like an anti pattern going at it this way.
const clickHandler = (e) => {
const relatedCard = e.target.closest(".card");
if (relatedCard) {
console.log("clickHandler", relatedCard.id);
} else {
console.log("click happened outside of a .card element");
}
};
A more react related solution would be to put the click handler on that element instead of the container div and use the id directly.
<div>
<div class="card" id="12345" onClick={() => clickHandler('12345')}>
<div class="x1">
<div class="x2">
<div class="">
<span class="">
<ul class="">
</div>
</div>
<div class="card" id="67890" onClick={() => clickHandler('67890')}>
<div class="x1">
<div class="x2">
<div class="">
<span class="">
<ul class="">
</div>
</div>
</div>
Upvotes: 1