react-bus-ts
A global event emitter for React apps. Useful if you need some user interaction in one place trigger an action in another place on the page, such as scrolling a logging element when pressing PageUp/PageDown in an input element (without having to store scroll position in state).
Usage
react-bus-ts contains a <ReactBusContext />
context and a withBus
decorator.
<ReactBusContext.Provider value={mitt()} />
creates an event emitter and places it on the context.
withBus()
takes the event emitter from context and passes it to the decorated component as the bus
prop.
;// Inject `bus` prop to <Component />.const ConnectedComponent = Componentconst emitter=; <ReactBusContextProvider value=emitter> <ConnectedComponent /></ReactBusContextProvider>
For example, to communicate "horizontally" between otherwise unrelated components. Context provider is optional - it is used to provide custom emitter instance.
const App = <div> <ScrollBox /> <Input /> </div>const ScrollBox = Component { thiselscrollTop += top } { thispropsbus } { thispropsbus } { return <div ref= thisel = el></div> }// Scroll the ScrollBox when pageup/pagedown are pressed.const Input = { return <input onKeyDown=onkeydown /> { if eventkey === 'PageUp' bus if eventkey === 'PageDown' bus }}
This may be easier to implement and understand than lifting the scroll state up into a global store.
Install
npm install react-bus-ts
API
<ReactBusContext.Provider value={emitter}>
Create an event emitter that will be available to all deeply nested child elements using the withBus()
function.
withBus(name='bus')(Component)
Wrap Component
and inject the event emitter as a prop named name
.