HiveBrain v1.2.0
Get Started
← Back to all entries
snippetreactCritical

How can I prevent event bubbling in nested React components on click?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
bubblingclickreacteventcomponentsnestedcanhowprevent

Problem

Here's a basic component. Both the ` and
  • have onClick functions. I want only the onClick on the
  • to 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
// => child

Solution

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.