Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/goto-bus-stop/react-bus
A global event emitter for react.
https://github.com/goto-bus-stop/react-bus
event-emitter pubsub react
Last synced: 6 days ago
JSON representation
A global event emitter for react.
- Host: GitHub
- URL: https://github.com/goto-bus-stop/react-bus
- Owner: goto-bus-stop
- License: mit
- Created: 2017-12-17T12:25:02.000Z (about 7 years ago)
- Default Branch: default
- Last Pushed: 2024-12-23T05:16:16.000Z (20 days ago)
- Last Synced: 2024-12-30T08:06:08.196Z (13 days ago)
- Topics: event-emitter, pubsub, react
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/react-bus
- Size: 50.8 KB
- Stars: 42
- Watchers: 3
- Forks: 5
- Open Issues: 3
-
Metadata Files:
- Readme: readme.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# react-bus
[![npm](https://badgen.net/npm/v/react-bus)](https://npmjs.com/package/react-bus)
[![bundlephobia](https://badgen.net/bundlephobia/minzip/react-bus)](https://bundlephobia.com/result?p=react-bus)A global [event emitter](https://github.com/developit/mitt) 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 contains a `` component and a `useBus` hook.
`` creates an event emitter and places it on the context.
`useBus()` returns the event emitter from context.```js
import { Provider, useBus } from 'react-bus'
// Use `bus` in .
function ConnectedComponent () {
const bus = useBus()
}
```
For example, to communicate "horizontally" between otherwise unrelated components:
```js
import { Provider as BusProvider, useBus, useListener } from 'react-bus'
const App = () => (
)function ScrollBox () {
const el = React.useRef(null)
const onscroll = React.useCallback(function (top) {
el.current.scrollTop += top
}, [])useListener('scroll', onscroll)
return
}// Scroll the ScrollBox when pageup/pagedown are pressed.
function Input () {
const bus = useBus()
returnfunction onkeydown (event) {
if (event.key === 'PageUp') bus.emit('scroll', -200)
if (event.key === 'PageDown') bus.emit('scroll', +200)
}
}
```This may be easier to implement and understand than lifting the scroll state up into a global store.
## Install
```
npm install react-bus
```## API
### ``
Create an event emitter that will be available to all deeply nested child elements using the `useBus()` hook.
### `const bus = useBus()`
Return the event emitter.
### `useListener(name, fn)`
Attach an event listener to the bus while this component is mounted. Adds the listener _after_ mount, and removes it before unmount.
## License
[MIT](./LICENSE)