preact-suber
v1.0.3
Published
Binding function 'withBus' between Preact and Suber
Downloads
39
Maintainers
Readme
Binding function withBus
between Preact and Suber.
Usage
Install:
yarn add preact-suber
# or
npm install preact-suber --save
Usage:
import preact from 'preact'
import { createBus } from 'suber'
import { withBus, BusProvider } from 'preact-suber'
// Create a component that will listen on the 'SHOW_WARNING' channel
// It expects 'bus' as a prop
class WarningBanner extends preact.Component {
constructor () {
super()
this.state = {
warning: null
}
}
componentDidMount() {
// Start listening for events on component mount
// When something arrives, set component state to the warning message
this.stop = this.props.bus.take('SHOW_WARNING', (msg) => {
this.setState({ warning: msg.warning })
})
}
componentWillUnmount() {
// Stop listening on unmount
this.stop()
}
render () {
// Show the warning (if present)
if (!this.state.warning) return null
return <blink>{ this.state.warning }</blink>
}
}
// Create a component will can send on the 'SHOW_WARNING' channel
// when clicked. It expects 'bus' as a prop
const SenderButton = ({ bus, children }) => {
const onClick = () => bus.send('SHOW_WARNING', { warning: 'Hacking detected!' })
return <button onClick={ onClick }>{ children }</button>
}
// To automatically pass the bus to these components
// we wrap them with 'withBus'
const WarningBannerWithBus = withBus(WarningBanner)
const SenderButtonWithBus = withBus(SenderButton)
// We use these wrapped components just as we
// would with the original components
// Remember to wrap your app in BusProvider to make the bus available
// for all components
const bus = createBus()
preact.render(
<BusProvider bus={bus}>
<WarningBannerWithBus />
<SenderButtonWithBus>Click me!!!</SenderButtonWithBus>
</BusProvider>
, document.getElementById('app')
)
API
Components
Functions
BusProvider
Provider component that makes the bus
available for withBus
through the context.
Attributes
bus: Object
A Suber bus. Import and invokecreateBus()
from Suber to create one.
withBus(component)
Returns the wrapped component with the bus
prop injected.
Arguments
component: Component
Preact component. Can be PureComponent or regular Component
Returns a new React Component
Development setup
yarn
npm run dev