React Mitt Save

React event emitter / pubsub 👉🏻👈🏽

Project README

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

Open Source Agenda is not affiliated with "React Mitt" Project. README Source: luqmanoop/react-mitt
Stars
29
Open Issues
2
Last Commit
3 years ago
License
MIT

Open Source Agenda Badge

Open Source Agenda Rating