I am trying to trigger a Function whenever I click on a Div, but that Div has an inner Div which means that If I click inside it it will trigger the onClick but on the wrong Div
I've looked around on Internet but couldn't find any answers.
A map function that returns the code below
<Card onClick={props.setSelectedTemplate} key={template.id} className="AdCopies" id={template.id.toString()}>
<SimpleAdCopy headlines={template.headlines} descriptions={template.descriptions} url={'www.google.com'}/>
</Card>
function handleClick(event) {
console.log(event.target.id)
}
I need the click to be always bounded to the outer div even if I click on the inner Div
You want to use event.currentTarget
instead of event.target
. target
is what was clicked, currentTarget
is the element the event was bound to.
As far as I understood it is about the React, isn't it? Anyway if you want to stop event bubbling ( https://www.sitepoint.com/event-bubbling-javascript/ ) you should add onClick handler to the inner div and inside a callback do something like this
<SimpleAdCopy onClick= {event => event.stopPropagation()} />
It stops event bubbling and lets you avoid onClick invocation on outer div
About stop propagation: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.