Skip to content

luqmanoop/react-mitt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

28 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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