react-mitt-forked
TypeScript icon, indicating that this package has built-in type declarations

1.0.5Β β€’Β PublicΒ β€’Β Published

react-mitt

React event emitter / pubsub

react-mitt build status react-mitt code coverage

A react wrapper for the awesome mitt library

Live demo https://codesandbox.io/s/react-mitt-demo-n11ii

Install

$ npm install react-mitt

Usage

Wrap your app in the MittProvider component, providing descendants access to the useMitt hook for event pubsub

import { MittProvider } from "react-mitt"

function App() {
  return (
    <MittProvider>
      <ComponentA />
      <ComponentB />
    </MittProvider>
  )
}

Example

Once you wrap your app with the MittProvider as demonstrated above, event pubsub becomes a breeze with the useMitt hook

import { useMitt } from 'react-mitt'

function ComponentA() {
  const { emitter } = useMitt()

  const handleClick = () => {
    emitter.emit('foo', { data: 'ComponentA says foo!'})
  }

  return <button onClick={handleClick}>emit!</button>
}

function ComponentB() {
  const { emitter } = useMitt()

  useEffect(() => {
    // listen and respond to 'foo' events
    emitter.on('foo', event => alert(event.data))
  }, [])

  return ...
}

Hook

The useMitt hook has the following signature

const { emitter } = useMitt()

For usage of the emitter object, see mitt API docs

License

MIT License

Package Sidebar

Install

npm i react-mitt-forked

Weekly Downloads

2

Version

1.0.5

License

MIT

Unpacked Size

9.15 kB

Total Files

10

Last publish

Collaborators

  • byzombies