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
Declarative API for installing global DOM event handlers #285
#284 reminded me that one thing I've sometimes wanted is to install a handler on window for keypress (for keyboard shortcuts) or scroll. Right now I can just do window.addEventListener in componentDidMount but since React is listening already, it would be nice if there were some way for me to intercept those events. (In addition, receiving normalized synthetic events is generally more useful.)
Reacted by Jake Goulding, Evan Jacobs, Yaroslav Kiliba, Maria Laura Rodriguez, Leandro Gonçalves de Oliveira, Ilnur Khalilov, Elad Ossadon, Philipp Spiess, Augustus Yuan, Julian Hollmann and 40 more
Reacted by Gustavo Cruz Pinheiro and Felipe Bonatti
Yes, I've wanted this for resize as well. We talked once about adding maybe a onWindowResize event that fires on every component, but how would it bubble?
I wanted this for mousemove and mouseup as well. :) We're thinking about a larger declarative event system that could do conflict resolution but we should probably get this in the mean time. Not sure about the API though.
@Aetet Sadly though, all of them operate on the assumption of US/Western keyboard layouts, unless you're willing to avoid support for ctrl and alt. Also, you could easily make this as a Mixin yourself.
@spicyj@petehunt As for this specific PR, what about simply exposing it as React.addEventListener(node, event, callback) (could be useful for when leaving the confines of React, like innerHTML) or as a mixin ReactEventsMixin + listenToEvents: [{event: callback}] which could then take care of the cleaning up itself.
Depending on the use-cases, I guess you could even do ReactWindowResizeMixin + handleWindowResize:, although you might end up with a lot of mixins. Again, depending on the size of the problem, you could even just have a single mixin that attaches to the events that have defined handlers/methods, handleWindowResize, etc.
The mixins could even be implemented as an addon, although it kind of feels like a "native" implementation would be nice.
Maybe it would be useful to consider a Flux Store-like solution here? Like some kind of ReactEvents store which wraps window-level events and emits synthetic events. Your components could subscribe and unsubscribe as they see fit.
onWindowResize: function(event){// do whatever you want in response to the resize event},componentDidMount: function(){this.subscription=ReactEvents.subscribe(ReactEvents.constants.WINDOW_RESIZE,this.onWindowResize);},componentWillUnmount: function(){this.subscription.remove();}
An API to hook events into the component events, like @glenjamin described, to produce synthetic events would be a nice thing to have.
this.events.fromEvent( ... ) // events on this components DOM representatoin
this.events.fromEventTarget( ... ) // events from other targets like "document"
I would recommend a look at the Bacon.js wrappers. Maybe a fromCallback binder would be great, too?
It needs to be useable declaratively ( like other events )
// inside the component:
render: function() {
return (
<div onMyEvent={handler} > test </div>
);
}
// from outside of the component, too? ( i do not think so )
<MyComponent onMyCusomEvent={eventhandler} />
and when could it be registered?
// before the first rendering, because of the custom event attribute
componendWillMount: function(events) {
events.fromEvent( ... ).as('onMyEvent')
}
With the advent of portals in React 16, it's the first time for me that React's event system has felt so dramatically different to that of the DOM. As I raised in #10962, the fact that events bubble through portals is very handy and so far seems to make logical sense, but is not something that works nicely with the current fallbacks to adding DOM events.
I think this divergence makes the need for such an API into React's event system even more relevant now.
Actually, none of the solutions mentioned above were sufficient for me, and I thought I had a pretty general case. I needed some simple global hotkeys. Binding them natively on document in component-did-mount worked of course, like other solutions using mousetrap or keymaster. The problem is, like @philipp-spiess illustrated, any other input field receiving synthetic keydowns and on which stopPropagation have been called are still fired up to the native document keydown listener. This is especially annoying when you have hotkeys that aren't prefixed (meta, alt, ctrl) like 'q' or 'v' => anytime a user inputs that key in an input field a global hot key would be called.
For anyone having the same problem, here's a neat little solution/trick I came up with that might help you and has not been offered in this thread or anywhere for that matter: Bind it twice - once on document, and once at the top of your react tree. The document handler checks if e.target == document.body (or whatever fits your needs), if so it fires. All the other ones are caught by the one bound to the react root. This way:
Global key events trigger hotkeys
Local key events can use stopPropagation to prevent the event from bubbling to the top of the react tree, or not and the hot key fires.
This can of course be applied to any other events, like clicks etc..
A very simple mockup of the idea
functiononKeyDown(e){// Handle global keydowns. !Warning: may receive native or synthetic events}functiononKeyDownNative(e){// Or whatever assertion works for your usecase, whatever is // "outside" of the react tree.if(e.target===document.body){onKeyDown(e);}}// Wrap this around the entire appclassHotkeyListenerextendsReact.Component{componentDidMount(){document.addEventListener("keydown",onKeyDownNative);}componentWillUnmount(){document.removeEventListener("keydown",onKeyDownNative);}render(){// Listens to any propagated synthetic keydown eventsreturn<divonKeyDown={onKeyDown}>{this.props.children}</div>;}}ReactDOM.render(<HotkeyListener>
// This input will propagate and trigger global key event through the synthetic event handler
<inputtype="text"/>
// This one will not
<inputtype="text"onKeyDown={(e)=>e.stopPropagation()}/></HotkeyListener>,document.getElementById("app"))
(Wow, no progress in five years? Doesn't Facebook itself support keyboard shortcuts and dismissing popups by clicking outside them?)
I got bitten by this today, when I refactored something from listening to keypresses on an <input> (in a React event) to using document.addEventListener (in a native event) – I was calling setState a lot, and suddenly not batching them made everything a lot laggier. I had to recover performance using ReactDOM.unstable_batchedUpdates.
In current React, it would make sense to offer this as hooks, which also do update batching on all listeners of the type. This would be a significant value add, as React is serving as a hub for all of our own code and react packages we depend on... to provide efficient updates.
Reacted by illia, Lezou Dali, Umair Ahmed, Abdullah Dahmash, Johannes Hansen and Leevi Halme
Activity
petehunt commentedon Aug 21, 2013
Yes, I've wanted this for
resizeas well. We talked once about adding maybe aonWindowResizeevent that fires on every component, but how would it bubble?andreypopp commentedon Aug 22, 2013
+1 on that, just encountered a case for that
If it fires on every component does it makes sense for it to bubble?
sebmarkbage commentedon Sep 6, 2013
I wanted this for mousemove and mouseup as well. :) We're thinking about a larger declarative event system that could do conflict resolution but we should probably get this in the mean time. Not sure about the API though.
sophiebits commentedon Sep 6, 2013
For mousemove and mouseup, I think @jordwalke was suggesting using ResponderEventPlugin…
sophiebits commentedon Sep 6, 2013
I'll also add that a way to bind to onbeforeunload declaratively could be helpful.
Aetet commentedon Feb 15, 2014
Also will be cool to have context keyDown. Like context hokeys for keyboard driven apps.
syranide commentedon Feb 18, 2014
@Aetet Sadly though, all of them operate on the assumption of US/Western keyboard layouts, unless you're willing to avoid support for
ctrlandalt. Also, you could easily make this as a Mixin yourself.@spicyj @petehunt As for this specific PR, what about simply exposing it as
React.addEventListener(node, event, callback)(could be useful for when leaving the confines of React, likeinnerHTML) or as a mixinReactEventsMixin+listenToEvents: [{event: callback}]which could then take care of the cleaning up itself.Depending on the use-cases, I guess you could even do
ReactWindowResizeMixin+handleWindowResize:, although you might end up with a lot of mixins. Again, depending on the size of the problem, you could even just have a single mixin that attaches to the events that have defined handlers/methods,handleWindowResize, etc.The mixins could even be implemented as an addon, although it kind of feels like a "native" implementation would be nice.
nick-thompson commentedon Aug 19, 2014
Maybe it would be useful to consider a Flux Store-like solution here? Like some kind of
ReactEventsstore which wraps window-level events and emits synthetic events. Your components could subscribe and unsubscribe as they see fit.glenjamin commentedon Sep 3, 2014
A couple of additional data points on this - the demo in http://kentwilliam.com/articles/rich-drag-and-drop-in-react-js mentions having to drop out of react events to do document listeners for mouse movements.
I've got a small module I put together for handing hotkeys that reaches into a bunch of React internals in order to produce synthetic keyboard events for document key events: https://github.com/glenjamin/react-hotkey/blob/master/index.js - providing a neat top-level listener that can be subscribed to, but forcing components to manage their own subscriptions' lifecycle seems like a reasonable tradeoff to me.
ThomasDeutsch commentedon Sep 5, 2014
An API to hook events into the component events, like @glenjamin described, to produce synthetic events would be a nice thing to have.
I would recommend a look at the Bacon.js wrappers. Maybe a fromCallback binder would be great, too?
It needs to be useable declaratively ( like other events )
and when could it be registered?
i think that is basically what @nick-thompson and @syranide were saying.
gasi commentedon Sep 23, 2014
👍 For React support
window-level events such askeydown,keyup, etc. for keyboard shortcuts.jsdir commentedon Sep 23, 2014
👍
vimto commentedon Sep 25, 2014
👍
pxwise commentedon Nov 14, 2014
👍
danyx23 commentedon Nov 29, 2014
👍
42 remaining items
jamiewinder commentedon Oct 4, 2017
With the advent of portals in React 16, it's the first time for me that React's event system has felt so dramatically different to that of the DOM. As I raised in #10962, the fact that events bubble through portals is very handy and so far seems to make logical sense, but is not something that works nicely with the current fallbacks to adding DOM events.
I think this divergence makes the need for such an API into React's event system even more relevant now.
Block: Cancel deselect via synthetic events
Block: Cancel deselect via synthetic events
yannvanhalewyn commentedon Mar 17, 2018
Actually, none of the solutions mentioned above were sufficient for me, and I thought I had a pretty general case. I needed some simple global hotkeys. Binding them natively on document in
component-did-mountworked of course, like other solutions using mousetrap or keymaster. The problem is, like @philipp-spiess illustrated, any other input field receiving synthetic keydowns and on whichstopPropagationhave been called are still fired up to the native document keydown listener. This is especially annoying when you have hotkeys that aren't prefixed (meta, alt, ctrl) like 'q' or 'v' => anytime a user inputs that key in an input field a global hot key would be called.For anyone having the same problem, here's a neat little solution/trick I came up with that might help you and has not been offered in this thread or anywhere for that matter: Bind it twice - once on document, and once at the top of your react tree. The document handler checks if
e.target == document.body(or whatever fits your needs), if so it fires. All the other ones are caught by the one bound to the react root. This way:stopPropagationto prevent the event from bubbling to the top of the react tree, or not and the hot key fires.This can of course be applied to any other events, like clicks etc..
A very simple mockup of the idea
Working demo on Codepen
Zarel commentedon Mar 31, 2018
(Wow, no progress in five years? Doesn't Facebook itself support keyboard shortcuts and dismissing popups by clicking outside them?)
I got bitten by this today, when I refactored something from listening to keypresses on an
<input>(in a React event) to usingdocument.addEventListener(in a native event) – I was callingsetStatea lot, and suddenly not batching them made everything a lot laggier. I had to recover performance usingReactDOM.unstable_batchedUpdates.brigand commentedon Mar 26, 2019
In current React, it would make sense to offer this as hooks, which also do update batching on all listeners of the type. This would be a significant value add, as React is serving as a hub for all of our own code and react packages we depend on... to provide efficient updates.
gaearon commentedon Aug 10, 2020
Regarding #285 (comment) in particular, we're switching React 17 to register events at the roots, which solves that particular case.
jesraygarciano commentedon Feb 19, 2024
perhaps close it already?
Work for issue react#285
povfarwa commentedon Jun 17, 2026
Test - security research
gogi005 commentedon Jun 24, 2026
Their issue - should FAIL
gogi005 commentedon Jun 24, 2026
Their issue in BATCH