npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-bus-esm

v1.3.1

Published

[![npm](https://badgen.net/npm/v/react-bus-esm)](https://npmjs.com/package/react-bus-esm) [![bundlephobia](https://badgen.net/bundlephobia/minzip/react-bus-esm)](https://bundlephobia.com/result?p=react-bus-esm)

Downloads

37

Readme

react-bus-esm

npm bundlephobia

A global event emitter for React apps which has support ES Modules and typescript. 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-esm contains a <Provider /> component and a useBus hook.

<Provider /> creates an event emitter and places it on the context. useBus() returns the event emitter from context.

import { Provider, useBus } from 'react-bus-esm'
// Use `bus` in <Component />.
function ConnectedComponent () {
  const bus = useBus()
}

<Provider>
  <ConnectedComponent />
</Provider>

For example, to communicate "horizontally" between otherwise unrelated components:

import { Provider as BusProvider, useBus, useListener } from 'react-bus-esm'
const App = () => (
  <BusProvider>
    <ScrollBox />
    <Input />
  </BusProvider>
)

function ScrollBox () {
  const el = React.useRef(null)
  const onscroll = React.useCallback(function (top) {
    el.current.scrollTop += top
  }, [])

  useListener('scroll', onscroll)

  return <div ref={el}></div>
}

// Scroll the ScrollBox when pageup/pagedown are pressed.
function Input () {
  const bus = useBus()
  return <input onKeyDown={onkeydown} />

  function 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.

Installing

You need to install react-bus-esm with react (@types/react for typescript users) and mitt as peer dependencies.

npm install react-bus-esm react mitt # add `@types/react` for typescript users

API

<Provider />

Create an event emitter that will be available to all deeply nested child elements using the useBus() hook.

You can also set mittOptions props to initialize global bus events with javascipt Map. e.g.:

import { Provider, useBus, EventHandlerMap } from 'react-bus-esm';

const options: EventHandlerMap = new Map()
options.set('test', [
  (payload) => { console.log(payload) },
  (...args: any[]) => { console.log(args) }
]) 

const ChildComponent = () => {
  const mittEventBus = useBus()
  const handleClick = () => {
    mittEventBus.emit('test', 'hello')
  }
  return (
    <button onClick={handleClick}>Submit</button>
  )
} 

const App = () => {
  const mittOptions = React.useRef(options)
  return (
    <React.StrictMode>
      <Provider mittOptions={mittOptions.current}>
        <ChildComponent />
      </Provider>
    </React.StrictMode>
  );
};

BusContext

In react-bus-esm, we share react context BusContext which beneficial for users which using this library in react class component. For typescript users, you need to import Emitter too. e.g.:

import { BusContext, Emitter } from 'react-bus-esm';

interface ClassComponentState {
  testPayloads: string[]
}

class ClassComponent extends React.PureComponent<{}, ClassComponentState> {
  declare context: Emitter
  // or context!: Emitter
  
  static contextType = BusContext

  state = {
    testPayloads: []
  }

  componentDidMount() {
    this.context.on<string>('test', (payload) => {
      this.setState(({ testPayloads }) => ({
        testPayloads: [
          ...testPayloads,
          payload as string
        ]
      }))
    })
  }

  render() {
    const { testPayloads } = this.state
    return testPayloads?.map((payload, index) => (
      <pre key={`test-payload-${index}`}>{payload}</pre>
    )) ?? false
  }
}

Emitter

return type of BusContext. Maybe, this interface will be deleted if React.ContextType<typeof BusContext> is Emitter, not unknown.

useBus()

Return the event emitter which can be used in react functional component.

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.

Inspiration

This library is inspired by react-bus, but unfortunately it doesn't support typescript. I have sent issue here but unfortunately no follow up after this.

It also has latest version of mitt, which has support typescript too since version 2.1.0.

License

MIT