snippetreactCritical
How can I prevent event bubbling in nested React components on click?
Viewed 0 times
bubblingclickreacteventcomponentsnestedcanhowprevent
Problem
Here's a basic component. Both the `
I've played around with e.preventDefault(), e.stopPropagation(), to no avail.
and have onClick functions. I want only the onClick on theto fire, not the`. How can I achieve this?
I've played around with e.preventDefault(), e.stopPropagation(), to no avail.
class List extends React.Component {
constructor(props) {
super(props);
}
handleClick() {
// do something
}
render() {
return (
{
console.log('parent');
this.handleClick();
}}
>
{
console.log('child');
// prevent default? prevent propagation?
this.handleClick();
}}
>
)
}
}
// => parent
// => childSolution
I had the same issue. I found stopPropagation did work. I would split the list item into a separate component, as so:
class List extends React.Component {
handleClick = e => {
// do something
}
render() {
return (
Item
)
}
}
class ListItem extends React.Component {
handleClick = e => {
e.stopPropagation(); //
{this.props.children}
)
}
}
Context
Stack Overflow Q#38619981, score: 307
Revisions (0)
No revisions yet.