You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
createPortal: support option to stop propagation of events in React tree #11387
Do you want to request a feature or report a bug?
Feature, but also a bug cause new API breaks old unstable_rendersubtreeintocontainer
What is the current behavior?
We cannot stop all events propagation from portal to its React tree ancestors. Our layers mechanism with modals/popovers completely broken. For example, we have a dropdown button. When we click on it, click opens popover. We also want to close this popover when clicking on same button. With createPortal, click inside popover fires click on button, and it's closing. We can use stopPropagation in this simple case. But we have tons of such cases, and we need use stopPropagation for all of them. Also, we cannot stop all events.
What is the expected behavior?
createPortal should have an option to stop synthetic events propagation through React tree without manually stopping every event. What do you think?
Reacted by Eliseu Monar dos Santos, Aloyzas Rimeika, Eugene Chapko, Marius Neimontas, Arnoldas, r-savcenko, James, Alexander Dorogin, Justas Vinevičius, Pavel Mickevic and 218 more
return[<divkey="main"><p>Hello! This is first step.</p><Buttonkey="button"/></div>,<Portalkey="portal"/>];
Then it won't bubble through the button.
Reacted by Bogdan Chadkin, Bradley Ayers, Johnson, Hen Greville, Alexey Avdeev, Alexander Dorogin, Vernon de Goede, Matt Hamlin, afc163, Daniel Playfair Cal and 8 more
Reacted by Evgeniy Kuvshinov, Aloyzas Rimeika, Anenth, Dominik Lubański, Michael Chou, Abdallatif Sulaiman, German Prostakov, Max Clayton Clowes, Ashlynne Mitchell, Stefanos Trialonis and 33 more
It was my first thought, but!) Imagine, that we have mouseEnter handler in such component container:
With unstable_rendersubtreeintocontainer i need nothing to do with events in ButtonWithPopover component – mouseEnter simply works when mouse really enters div and button DOM element, and not fired when mouse is over popover. With portal, event fires when mouse over popover – and actually NOT over div in this moment. So, i need to stop propagation. If i do it in ButtonWithPopover component, i will break event firing when mouse is over button. If i do it in popover and i'm using some common popover component for this application, i also can break logic in other app parts.
I really don't understand purpose of bubbling through React tree. If i need events from portal component – i simply can pass handlers through props. We were do it with unstable_rendersubtreeintocontainer and it worked perfect.
If i will open a modal window from some button deep in react tree, i will receive unexpected firing of events under modal. stopPropagation will also stop propagation in DOM, and i will not get events that i really expect to be fired(
Reacted by Aloyzas Rimeika, Alexander Dorogin, Justas Vinevičius, aaduevsky, jershell, James Wagoner, Menny Rachmanny (onemenny), Limbo Sounds, Aneree, Victor Hallberg and 19 more
@gaearon I would suggest this is more of a bug than a feature request. We have a number of new bugs caused by mouse events bubbling up through portals (where we were previously using unstable_rendersubtreeintocontainer). Some of these can't be fixed even with an extra div layer to filter mouse events because e.g. we rely on mousemove events propagating up to the document to implement draggable dialogs.
Is there a way to workaround this before this is addressed in a future release?
Reacted by Louis Roman, Adam Rackis, yury-yufimov, Andreas, Sergey M., ehab-cl, Maxim Kulikov, Tobi and Dmitriy Petrov
I think it's being called a feature request, because the current bubble behavior of portals is both expected and intended. The goal is that subtree act like real child of their parents.
What would be helpful is additional use cases or situations (like the ones you're seeing) that you don't feel are served by the current implementation, or are difficult to workaround
I understand that this behavior is intended, but I think it's a significant bug that it's not disable-able.
Reacted by jershell, Sébastien Lorber, Jeff Margolis, Arseniy, Dave Porter, Dmitry Druganov, Renato Ribeiro, Sergio Pereira, C D, Adam Rackis and 7 more
In my mind library working with DOM should preserve DOM implementation behavior not break it.
For example:
classContainerextendsReact.Component{shouldComponentUpdate=()=>false;render=()=>(<divref={this.props.containerRef}// Event propagation on this element not workingonMouseEnter={()=>{console.log('handle mouse enter');}}onClick={()=>{console.log('handle click');}}/>)}classRootextendsReact.PureComponent{state={container: null};handleContainer=(container)=>{this.setState({ container });}render=()=>(<div><div// Event propagation on this element not working alsoonMouseEnter={()=>{console.log('handle mouse enter');}}onClick={()=>{console.log('handle click');}}><ContainercontainerRef={this.handleContainer}/></div>{this.state.container&&ReactDOM.createPortal(<div>Portal</div>,this.state.container)}</div>);}
When I work with DOM, I expect to receive events like DOM implementation does it. In my example events are propagated through Portal, working around it's DOM parents, and this can be considered as a bug.
Reacted by Craig Kovatch, Evgeniy Kuvshinov, Menny Rachmanny (onemenny), Sébastien Lorber, Alastair Taft, Peter Hozák, Sebastian Cruz, Ben, Hideman85, James Mikrut and 12 more
Folks thanks for the discussion, however I don't think it's all that helpful to argue whether something is a bug or not. Instead i'd be more productive to discuss the use cases and examples that are not met by the current behavior, so we can better understand if the current way is the best way for the future.
In general we want the API to handle a diverse set of use-cases while hopefully not overly limiting others. I can't speak for the core team, but I'd imagine that making it configurable is not a likely solution. Generally React leans for a consistent api over configurable ones.
I also understand that this behavior is not how the DOM works, but i don't think that's in itself a good reason to say it shouldn't be that way. Lots of react-dom's behavior is different from how the DOM works, may events are already different from the native version. onChange for instance is completely unlike the native change event, and all react events bubble regardless of type, unlike the DOM.
Reacted by timspiers, Kevin Johnson, Olivier Tassinari, Klynger and Entkenntnis
Instead i'd be more productive to discuss the use cases and examples that are not met by the current behavior
Here's two examples that are broken for us in our migration to React 16.
First, we have a draggable dialog which is launched by a button. I attempted to add a "filtering" element on our Portal use which called StopPropagation on any mouse* an key* events. However, we rely on being able to bind a mousemove event to the document in order to implement the dragging functionality -- this is common because if the user moves the mouse at any significant rate, the cursor leaves the bounds of the dialog and you need to be able to capture the mouse movement at a higher level. Filtering these events breaks this functionality. But with Portals, the mouse and key events are bubbling up from inside the dialog to the button that launched it, causing it to display different visual effects and even dismiss the dialog. I don't think it's realistic to expect every component that will be launched via a Portal to bind 10-20 event handlers to stop this event propagation.
Second, we have a popup context menu which can be launched by either a primary- or secondary-mouse click. One of the internal consumers of our library has mouse handlers attached to the element that launches this menu, and of course the menu also has click handlers for handling item selection. The menu is now reappearing on every click as the mousedown/mousedown events are bubbling back up to the button that launches the menu.
I can't speak for the core team, but I'd imagine that making it configurable is not a likely solution. Generally React leans for a consistent api over configurable ones.
I implore you (and the team) to reconsider this position in this particular case. I think event bubbling will be interesting for certain use cases (although I can't think of any offhand). But I think it will be crippling in others, and it introduces significant inconsistency in the API. While unstable_rendersubtreeintocontainer was never super-supported, it was what everyone used to render outside of the immediate tree, and it didn't work this way. It was officially deprecated in favor of Portals, but Portals break the functionality in this critical way, and there doesn't seem to be an easy workaround. I think this can be fairly described as quite inconsistent.
I also understand that this behavior is not how the DOM works, but i don't think that's in itself a good reason to say it shouldn't be that way.
I understand where you're coming from here, but I think in this case (a) it's a fundamental behavior which (b) currently has no workaround, so I think "the DOM doesn't work this way" is a strong argument, if not a completely convincing one.
Reacted by Aloyzas Rimeika, Eliseu Monar dos Santos, riccardov, Raman Khakhlou, Stephan Bijzitter, Aaron Lademann, Will Stamper, Victor Hallberg, Andrew Maksimchenko and Luca Martins
My mental model of a Portal is that it behaves as if it is on the same place in the tree, but avoids problems such as "overflow: hidden" and avoids scrolling for drawing/layout purposes.
There are many similar "popup" solutions that happen inline without a Portal. E.g. a button that expands a box right next to it.
Take as an example the "Pick your reaction" dialog here on GitHub. That is implemented as a div right next to the button. That works fine now. However, if it wants to have a different z-index, or be lifted out of an overflow: scroll area that contains these comments, then it will need to change DOM position. That change is not safe to do unless other things like event bubbling is also preserved.
Both styles of "popups" or "pop outs" are legit. So how would you solve the same problem when the component is inline in the layout as opposed to floating outside of it?
Reacted by Timur Seitosmanov, Benoît Grélard, Benjamin and Ken Gregory
@methyl this assumes you know every event that you need to block from bubbling up the tree. And in the case I mentioned with draggable dialogs, we need mousemove to bubble up to document, but not to bubble up the render tree.
Reacted by Lucjan Suski, Raman Khakhlou, Prateek Jain, Stephan Bijzitter, Victor Hallberg, Lorenzo Stanco, Laurin, Avele, Stefan K, Andreas and 7 more
We ran across this issue yet again in React Aria. Seriously considering adding this to all of our overlay components to hopefully solve it once and for all. 😐
Unfortunately, even if we add that to our overlays, it won't prevent propagation out of other portals that people might use with React Aria, so we also have to add checks like this in most of our event handlers:
if(!e.currentTarget.contains(e.target)){return;}
This fixes event handlers that we control, but doesn't fix custom event handlers added by consumers, who would also need to do that unless the portal itself also stopped propagation as above.
React itself is the common thread here, so ideally React portals themselves should not stop propagation by default. Otherwise it's easy to get wrong and cause bugs by using different combinations of portal components and components with event handlers from different libraries that may or may not have these checks.
Reacted by Armand Bernard, Aaron HS, Emmanuel Meric de Bellefon, Erik Brendel, Joshua Wootonn, Caroline Liu, Mykhaylo Ryechkin and rjgotten
Reacted by Victor Hallberg, thezjy, Dave Porter, Craig Kovatch, Yassien, Aaron Reisman and Caroline Liu
I'm currently working on a bug from five years ago that goes all the way back to this issue. Really sad this has been here since Oct 2017 with no official response at all. I think this is the worst API decision decision in React and am confused why there's still no ...whatever the opposite of an escape hatch is
Reacted by Joshua Chamberlain, Phil Xu, kostia-lev, croraf, Maroš Beťko, Jessie G., Yassien, Sebastian, Jason Sims and Marco Pinton
Stopping propagation is NOT a solution, sometimes you want to handle events further down the line or on the document. It makes perfect sense to be able to propagate events according to their natural location in the DOM (i'd argue even more sense than what we have now)
Like many others in this thread I'm now facing an issue where nested elements that use portals propagate events and affect each other in weird illogical ways, with no straight forward way to fix it.
Reacted by Victor Hallberg, Andreas, Gian Marco Toso, Alexander Dmitrievich, Jason Sims, Jacky.Y, Dmitriy Petrov and Gabriella Moses
This behavior has caused numerous bugs in my component library. Event propagation should mirror the way native events propagate in the DOM. I can't think of any reason why I'd want events to propagate through the component tree when it differs from the DOM hierarchy (i.e. across portal boundaries), but if there is one, it should be necessary to opt into that behavior, as it's counterintuitive and breaks expectations about how events work.
As others have mentioned, stopping event propagation is not a viable solution. There are numerous reasons why event propagation should (almost) never be stopped. If you want things like dropdowns and popovers to close when clicking outside of them, the only reasonable approach is to add an event listener to document.body. If something receives a click and stops propagation, it won't work.
If you run into a situation where you need to ignore an event when it's already been handled by something else, you can add a property to the event (I use event.eventHandled = true, or in React components, event.nativeEvent.eventHandled = true), then ignore events that have that property, as needed. Indeed, that's also how I fix each of the bugs caused by the decision to have events bubble up the component tree without respect for the DOM hierarchy.
I think this behavior should be off by default and enabled on a per-portal basis (perhaps as an argument to createPortal). It has only ever caused problems for me, and I've never encountered a situation where it would actually be useful.
Reacted by Victor Hallberg, Fabio Salvini, Marco Pinton and Kostiantyn Ko
While .stopPropagation do work most of the time, there are cases when you want bubble it for only the document and skipping every other parent. ie. A modal with mouse events for drag and drop. We ended up dispatching a cloned event specifically for the document (global events).
@sebmarkbage is there any chance you guys will provide a solution to this problem in the near future? I've run into this countless times and its really unfortunate that it still hasn't been addressed 🤕
Reacted by Mykhaylo Ryechkin, Adam Pietrasiak, Dave Porter, Marco Pinton, Dmitriy Petrov, Ed Olivares and Ritik
function Example() {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<>
<Button variant="primary" onClick={handleShow}>
Launch demo modal
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you are reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</>
);
}
To:
function Example() {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<>
<Button variant="primary" onClick={handleShow}>
Launch demo modal
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you are reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</Button>
</>
);
}
With the second component you can exit using only esc button. Of course, this is not a real-world example, but when you have layered components in a large codebase, you can easily run into this issue.
Insane to me that this hasn't been resolved after 7 years of the community complaining. Clearly a bad initial API design. stopPropagation is not a real solution - and only leads to finicky bugs later down the line.
Reacted by Dave Porter, Aaron Reisman, Bodo Tasche, Marco Pinton, puchm, Quentin Grangé , Abdolah Keshtkar, Fabio Salvini, Anton Ustinov, Dmitriy Petrov and 3 more
@jasosims
If you want things like dropdowns and popovers to close when clicking outside of them, the only reasonable approach is to add an event listener to document.body. If something receives a click and stops propagation, it won't work.
If you're just dealing with things like custom styled selects, aka role="combobox" from ARIA, then there's a better way.
You keep the native browser focus on the opener element and use virtual focus with aria-activedescendant to track focused items within the list. And you close the dropdown popover when the opener loses focus. Which means automatically the case where your end-user uses any type of keyboard navigation, whether (Shift+)Tab, arrow keys with roving focus in a role="toolbar" or otherwise, is also covered.
For those cases where you need to actually be able to tap on multiple elements before a popover closes (e.g. if you make a dropdown list aria-multiselectable="true") you can make it work with a fairly simple recipe, as long as you have a ref to the popup DOM element and use native event handlers. (This doesn't work with React's synthetic events.)
set touchAction = "pan" on the list element to ensure scrolling gestures will cancel touches and pointer events and no other native interactions are allowed to intercept touch handling.
attach a mousedown listener with { capture: true, passive: false } that calls event.preventDefault()
attach a touchend listener with { capture: true, passive: false } that calls event.preventDefault()
attach a pointerup listener with { capture: true, passive: false } that checks whether event.isPrimary and event.pointerType == "touch" and if so, use the pointer event to create a new PointerEvent of type "click" and dispatch it off of event.target.
This blocks focus moving off of the opener element, but does still give you a working click event on whatever is inside your popover that you can then work with. Strangely, cancelling default behavior on mousedown during capture seems to cancel focus movement - but not the dispatch of a native click event. A curiosity not shared by cancelling touchend, which is why that one goes paired with pointerup to spin off a new 'click' event off of the pointerup event. (In case you didn't know: click events are of type PointerEvent nowadays. So you can synthesize one by copying over most of the pointerup event's properties. Crucially: including things like the keyboard modifier key state properties.)
This is a portable recipe that can easily be encapsulated into a custom hook, and afaik works on all major browsers.
Write once. Use everywhere.
Do note though, that for the entire pattern to work, the opener must actually be given real focus when clicked, so focus can move away from it when clicking elsewhere.
Which, even in the year 2025, is still not the case on Apple devices and Webkit. They don't actually make e.g. buttons the focused element when clicked on with a pointer device or tapped on via touch. You need to explicitly call event.currentTarget.focus() in a click handler for them.
This terrible feature of React portals is annoying every time you encounter it
I fully support that we need an option to disable this behavior.
Can we add it?
Maybe like this:
// currently key is third argument// we can improve function by allowing to pass options object as third argumentcreatePortal(children,element,{ key,eventPropagation: false})
Reacted by Ronald Ruzicka, Itamar Yatom, Aaron Reisman, Ritik, Zane, Kevin Kröger, Peter Lenahan, Victor Hallberg and Fabio Salvini
I always assumed this was a bug with the component libraries I use. TIL it's a React issue.
I like React very much when it doesn't enforce opinionated stuff. But this is quite bad. The only reparenting feature in React has this issue, without a way to disable it. Do I have to implement a custom portal now too?
Reacted by Victor Hallberg, Dmitriy Petrov and rjgotten
Activity
kib357 commentedon Oct 27, 2017
Also, propagation of mouseOver/Leave looks completely unexpected.

gaearon commentedon Oct 27, 2017
Can you move portal outside of the button?
e.g.
Then it won't bubble through the button.
kib357 commentedon Oct 28, 2017
It was my first thought, but!) Imagine, that we have mouseEnter handler in such component container:
With
unstable_rendersubtreeintocontaineri need nothing to do with events inButtonWithPopovercomponent – mouseEnter simply works when mouse really entersdivand button DOM element, and not fired when mouse is over popover. With portal, event fires when mouse over popover – and actually NOT overdivin this moment. So, i need to stop propagation. If i do it inButtonWithPopovercomponent, i will break event firing when mouse is over button. If i do it in popover and i'm using some common popover component for this application, i also can break logic in other app parts.I really don't understand purpose of bubbling through React tree. If i need events from portal component – i simply can pass handlers through props. We were do it with
unstable_rendersubtreeintocontainerand it worked perfect.If i will open a modal window from some button deep in react tree, i will receive unexpected firing of events under modal.
stopPropagationwill also stop propagation in DOM, and i will not get events that i really expect to be fired(craigkovatch commentedon Jan 3, 2018
@gaearon I would suggest this is more of a bug than a feature request. We have a number of new bugs caused by mouse events bubbling up through portals (where we were previously using
unstable_rendersubtreeintocontainer). Some of these can't be fixed even with an extra div layer to filter mouse events because e.g. we rely on mousemove events propagating up to the document to implement draggable dialogs.Is there a way to workaround this before this is addressed in a future release?
jquense commentedon Jan 3, 2018
I think it's being called a feature request, because the current bubble behavior of portals is both expected and intended. The goal is that subtree act like real child of their parents.
What would be helpful is additional use cases or situations (like the ones you're seeing) that you don't feel are served by the current implementation, or are difficult to workaround
craigkovatch commentedon Jan 3, 2018
I understand that this behavior is intended, but I think it's a significant bug that it's not disable-able.
neytema commentedon Jan 3, 2018
In my mind library working with DOM should preserve DOM implementation behavior not break it.
For example:
When I work with DOM, I expect to receive events like DOM implementation does it. In my example events are propagated through Portal, working around it's DOM parents, and this can be considered as a bug.
jquense commentedon Jan 3, 2018
Folks thanks for the discussion, however I don't think it's all that helpful to argue whether something is a bug or not. Instead i'd be more productive to discuss the use cases and examples that are not met by the current behavior, so we can better understand if the current way is the best way for the future.
In general we want the API to handle a diverse set of use-cases while hopefully not overly limiting others. I can't speak for the core team, but I'd imagine that making it configurable is not a likely solution. Generally React leans for a consistent api over configurable ones.
I also understand that this behavior is not how the DOM works, but i don't think that's in itself a good reason to say it shouldn't be that way. Lots of react-dom's behavior is different from how the DOM works, may events are already different from the native version.
onChangefor instance is completely unlike the native change event, and all react events bubble regardless of type, unlike the DOM.craigkovatch commentedon Jan 3, 2018
Here's two examples that are broken for us in our migration to React 16.
First, we have a draggable dialog which is launched by a button. I attempted to add a "filtering" element on our Portal use which called StopPropagation on any mouse* an key* events. However, we rely on being able to bind a mousemove event to the document in order to implement the dragging functionality -- this is common because if the user moves the mouse at any significant rate, the cursor leaves the bounds of the dialog and you need to be able to capture the mouse movement at a higher level. Filtering these events breaks this functionality. But with Portals, the mouse and key events are bubbling up from inside the dialog to the button that launched it, causing it to display different visual effects and even dismiss the dialog. I don't think it's realistic to expect every component that will be launched via a Portal to bind 10-20 event handlers to stop this event propagation.
Second, we have a popup context menu which can be launched by either a primary- or secondary-mouse click. One of the internal consumers of our library has mouse handlers attached to the element that launches this menu, and of course the menu also has click handlers for handling item selection. The menu is now reappearing on every click as the mousedown/mousedown events are bubbling back up to the button that launches the menu.
I implore you (and the team) to reconsider this position in this particular case. I think event bubbling will be interesting for certain use cases (although I can't think of any offhand). But I think it will be crippling in others, and it introduces significant inconsistency in the API. While
unstable_rendersubtreeintocontainerwas never super-supported, it was what everyone used to render outside of the immediate tree, and it didn't work this way. It was officially deprecated in favor of Portals, but Portals break the functionality in this critical way, and there doesn't seem to be an easy workaround. I think this can be fairly described as quite inconsistent.I understand where you're coming from here, but I think in this case (a) it's a fundamental behavior which (b) currently has no workaround, so I think "the DOM doesn't work this way" is a strong argument, if not a completely convincing one.
craigkovatch commentedon Jan 3, 2018
And to be clear: my request that this be considered a bug is mostly so that it gets prioritized for a fix sooner rather than later.
sebmarkbage commentedon Jan 4, 2018
My mental model of a Portal is that it behaves as if it is on the same place in the tree, but avoids problems such as "overflow: hidden" and avoids scrolling for drawing/layout purposes.
There are many similar "popup" solutions that happen inline without a Portal. E.g. a button that expands a box right next to it.
Take as an example the "Pick your reaction" dialog here on GitHub. That is implemented as a div right next to the button. That works fine now. However, if it wants to have a different z-index, or be lifted out of an
overflow: scrollarea that contains these comments, then it will need to change DOM position. That change is not safe to do unless other things like event bubbling is also preserved.Both styles of "popups" or "pop outs" are legit. So how would you solve the same problem when the component is inline in the layout as opposed to floating outside of it?
methyl commentedon Jan 4, 2018
The workaround that worked for me is calling
stopPropagationdirectly under portal rendering:That works great for me since I have single abstraction component that uses portals, otherwise you will need to fix up all your
createPortalcalls.craigkovatch commentedon Jan 4, 2018
@methyl this assumes you know every event that you need to block from bubbling up the tree. And in the case I mentioned with draggable dialogs, we need
mousemoveto bubble up to document, but not to bubble up the render tree.118 remaining items
devongovett commentedon May 16, 2023
We ran across this issue yet again in React Aria. Seriously considering adding this to all of our overlay components to hopefully solve it once and for all. 😐
Unfortunately, even if we add that to our overlays, it won't prevent propagation out of other portals that people might use with React Aria, so we also have to add checks like this in most of our event handlers:
This fixes event handlers that we control, but doesn't fix custom event handlers added by consumers, who would also need to do that unless the portal itself also stopped propagation as above.
React itself is the common thread here, so ideally React portals themselves should not stop propagation by default. Otherwise it's easy to get wrong and cause bugs by using different combinations of portal components and components with event handlers from different libraries that may or may not have these checks.
craigkovatch commentedon Jun 13, 2023
I'm currently working on a bug from five years ago that goes all the way back to this issue. Really sad this has been here since Oct 2017 with no official response at all. I think this is the worst API decision decision in React and am confused why there's still no ...whatever the opposite of an escape hatch is
zombieJ commentedon Oct 27, 2023
Hmmm...
I could not remember how many times I track and found this issue...
yy-96 commentedon Nov 6, 2023
Stopping propagation is NOT a solution, sometimes you want to handle events further down the line or on the document. It makes perfect sense to be able to propagate events according to their natural location in the DOM (i'd argue even more sense than what we have now)
Like many others in this thread I'm now facing an issue where nested elements that use portals propagate events and affect each other in weird illogical ways, with no straight forward way to fix it.
jasosims commentedon May 2, 2024
This behavior has caused numerous bugs in my component library. Event propagation should mirror the way native events propagate in the DOM. I can't think of any reason why I'd want events to propagate through the component tree when it differs from the DOM hierarchy (i.e. across portal boundaries), but if there is one, it should be necessary to opt into that behavior, as it's counterintuitive and breaks expectations about how events work.
As others have mentioned, stopping event propagation is not a viable solution. There are numerous reasons why event propagation should (almost) never be stopped. If you want things like dropdowns and popovers to close when clicking outside of them, the only reasonable approach is to add an event listener to
document.body. If something receives a click and stops propagation, it won't work.If you run into a situation where you need to ignore an event when it's already been handled by something else, you can add a property to the event (I use
event.eventHandled = true, or in React components,event.nativeEvent.eventHandled = true), then ignore events that have that property, as needed. Indeed, that's also how I fix each of the bugs caused by the decision to have events bubble up the component tree without respect for the DOM hierarchy.I think this behavior should be off by default and enabled on a per-portal basis (perhaps as an argument to
createPortal). It has only ever caused problems for me, and I've never encountered a situation where it would actually be useful.vrajpal-jhala commentedon May 10, 2024
While
.stopPropagationdo work most of the time, there are cases when you want bubble it for only the document and skipping every other parent. ie. A modal with mouse events for drag and drop. We ended up dispatching a cloned event specifically for the document (global events).AbdelrahmanAbounida commentedon Jun 11, 2024
I solved it like that
fix(FormField): check focus event target to counter bubbling from por…
lifeiscontent commentedon Aug 28, 2024
@sebmarkbage is there any chance you guys will provide a solution to this problem in the near future? I've run into this countless times and its really unfortunate that it still hasn't been addressed 🤕
Add ModalWithoutOnClickPropagation (#338)
ElSalvo96 commentedon Nov 5, 2024
Hello, I encountered the same issue with this version in my company's UI Library:
I also found an easy way to run into this issue.
Just go there https://react-bootstrap.netlify.app/docs/components/modal/#live-demo and edit the component from:
To:
With the second component you can exit using only esc button. Of course, this is not a real-world example, but when you have layered components in a large codebase, you can easily run into this issue.
tobq commentedon Dec 5, 2024
Insane to me that this hasn't been resolved after 7 years of the community complaining. Clearly a bad initial API design.
stopPropagationis not a real solution - and only leads to finicky bugs later down the line.rjgotten commentedon Apr 2, 2025
If you're just dealing with things like custom styled selects, aka
role="combobox"from ARIA, then there's a better way.You keep the native browser focus on the opener element and use virtual focus with
aria-activedescendantto track focused items within the list. And you close the dropdown popover when the opener loses focus. Which means automatically the case where your end-user uses any type of keyboard navigation, whether (Shift+)Tab, arrow keys with roving focus in arole="toolbar"or otherwise, is also covered.For those cases where you need to actually be able to tap on multiple elements before a popover closes (e.g. if you make a dropdown list
aria-multiselectable="true") you can make it work with a fairly simple recipe, as long as you have a ref to the popup DOM element and use native event handlers. (This doesn't work with React's synthetic events.)touchAction = "pan"on the list element to ensure scrolling gestures will cancel touches and pointer events and no other native interactions are allowed to intercept touch handling.mousedownlistener with{ capture: true, passive: false }that callsevent.preventDefault()touchendlistener with{ capture: true, passive: false }that callsevent.preventDefault()pointeruplistener with{ capture: true, passive: false }that checks whetherevent.isPrimaryandevent.pointerType == "touch"and if so, use the pointer event to create a newPointerEventof type"click"and dispatch it off ofevent.target.This blocks focus moving off of the opener element, but does still give you a working click event on whatever is inside your popover that you can then work with. Strangely, cancelling default behavior on
mousedownduring capture seems to cancel focus movement - but not the dispatch of a nativeclickevent. A curiosity not shared by cancellingtouchend, which is why that one goes paired withpointerupto spin off a new 'click' event off of thepointerupevent. (In case you didn't know: click events are of typePointerEventnowadays. So you can synthesize one by copying over most of thepointerupevent's properties. Crucially: including things like the keyboard modifier key state properties.)This is a portable recipe that can easily be encapsulated into a custom hook, and afaik works on all major browsers.
Write once. Use everywhere.
Do note though, that for the entire pattern to work, the opener must actually be given real focus when clicked, so focus can move away from it when clicking elsewhere.
Which, even in the year 2025, is still not the case on Apple devices and Webkit. They don't actually make e.g. buttons the focused element when clicked on with a pointer device or tapped on via touch. You need to explicitly call
event.currentTarget.focus()in a click handler for them.krutoo commentedon May 7, 2025
This terrible feature of React portals is annoying every time you encounter it
I fully support that we need an option to disable this behavior.
Can we add it?
Maybe like this:
gkurt commentedon Mar 26, 2026
I always assumed this was a bug with the component libraries I use. TIL it's a React issue.
I like React very much when it doesn't enforce opinionated stuff. But this is quite bad. The only reparenting feature in React has this issue, without a way to disable it. Do I have to implement a custom portal now too?