1

Consider this test case:

const Component = (() =>
  <div onClickCapture={(e) => console.log('div click capture')}
    onClick={(e) => console.log('div click bubble')}>
    <input type='checkbox'
      onClickCapture={(e) => console.log('checkbox click capture')}
      onClick={(e) => console.log('checkbox click bubble')} />
  </div>
)

const placeholder = document.getElementById('placeholder')
placeholder.addEventListener('click',
  (e) => console.log('placeholder click capture'),
  /* useCapture= */true)
placeholder.addEventListener('click',
  (e) => console.log('placeholder click bubble'),
  /* useCapture= */false)

ReactDOM.render(<Component />, placeholder)
  • A "placeholder" element in the HTML, with listeners attached.
  • Two React elements mounted to the placeholder, themselves with React listeners attached.

React uses event delegation and handles its listeners after the document, which means clicking the checkbox results in a log like this:

placeholder click capture
placeholder click bubble
div click capture
checkbox click capture
checkbox click bubble
div click bubble

I'm developing a browser extension that mounts new components in the page. I chose to go with React, and this feature is making it difficult to mount new components as descendants of existing elements that already have listeners attached. If I attach a listener to the mount point that calls event.stopPropagation(), then it also stops the event from reaching the document and thus being handled by React. Is there a way to let React handle events "inside" the mount point without letting them bubble out of the React mount point? In other words, to keep events scoped to the virtual DOM?

John Freeman
  • 2,552
  • 1
  • 27
  • 34
  • Why are you adding event listeners outside of the framework? – jmargolisvt Jan 29 '17 at 19:41
  • Not sure how that is relevant to the answer, but like I said in the question, I'm developing a browser extension that adds a small UI to an existing page with existing listeners. I'm not adding any listeners outside the framework. – John Freeman Jan 29 '17 at 20:14

0 Answers0