Reputation: 77
I know this kind of questions has been asked before but here I have a problem where I have a clickable cards and a component in a card which is button, onclick whole card is being clicked,but i want a button to be clicked on click of button and card onclick of card. how can i render both the events? How can i use target for both the events? I am newbie to react,could someone help me to render both.
Current onclick code:
handleClick = (event) => {
console.log("cards click");
event.preventDefault();
};
handleSubmit(event) {
console.log("button inside card click");
const target = event.target;
}
Upvotes: 0
Views: 3866
Reputation: 171
This is called event bubbling. Where event is passed from child to parent.
event.stoppropagation() stops it.
You can just pass event.target into your handler and check if handler should be executed based on properties of target. For example you can check by:
handleClick = (e) => { if (e.target.name /type/id == your desired name/type/id) { then your code, e.stop.propagation()}
After your deaired code is executed. e.stopPropagation() will stop the bubbling of the event to its parent.
Upvotes: 0
Reputation: 1
you can use event.preventDefault();
inside button click event
function handleSubmit(event) {
event.preventDefault();
console.log("button inside card click");
}
Upvotes: 0
Reputation: 757
If you are wanting the Card onClick event to execute unless the button is pressed, in which case you want the handleSubmit function instead, then I would put the card click function in an if loop to filter by event target type:
handleClick = (e) => { if (e.target.type !== button) { code for click event }}
Upvotes: 0
Reputation: 5298
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
This process is called event bubbling, learn more here.
To fix your issue, you have to call event.stopPropagation()
inside your button's event handler.
export default function App() {
function handleClick(event) {
console.log("cards click");
}
function handleSubmit(event) {
event.stopPropagation(); // notice this
console.log("button inside card click");
}
return (
<div className="card" onClick={handleClick}>
<button onClick={handleSubmit}>BUTTON INSIDE CARD</button>
</div>
);
}
Upvotes: 3