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

1.0.1Ā ā€¢Ā 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

Weekly Downloads

305

Version

1.0.1

License

MIT

Unpacked Size

8.89 kB

Total Files

10

Last publish

Collaborators

  • codeshifu