React-PubSub is an abstraction layer for React. The idea is to enable PubSub communication between React components, completely decoupling the PubSub layer and its consumption.
React-PubSub enable support to any compliant PubSub libray via custom adapters
.
The library is just 14kB and comes with an internal PubSub implementation ready to be used out of the box.
React-Pubsub requires React 0.14 or later.
If you are using webpack or browserify to manage the project dependencies:
npm install --save react-pubsub
If you are using bower or other build system an UMD build is available at unpkg.com:
- UMD uncompressed: react-pubsub.js
- UMD compressed: react-pubsub.min.js
Using the UMD build react-pubsub
is available as a global object.
React-SubPub should work without problems with React Native, but we've not already tried it.
React-PubSub offers 3 elements:
- a PubSub Wrapper
- a PubSub Provider
- a PubSub Connector
To start using it you must create a PubSub Wrapper and passit to a PubSub Provider. The Provider will expose to its children the PubSub Wrapper API.
// App.js
import React, { Component } from 'react';
import { createPubSub, PubSubProvider } from 'react-pubsub';
import ConnectedComponent from './ConnectedComponent';
const pubSubCore = createPubSub();
export default class App extends Component {
render() {
return (
<PubSubProvider pubSubCore={pubSubCore}>
<div>{ .... }</div>
</PubSubProvider>
);
}
}
Any children of PubSubProvider who require access to the PubSub API should be wrapped by a PubSub Connector.
The connector will pass pubSub
as prop to its child component.
Create the Connected Component:
// ConnectedComponent.js
import React, { Component, PropTypes } from 'react';
import { createPubSubConnector } from 'react-pubsub';
class ConnectedComponent extends Component {
componentDidMount() {
const { pubSub } = this.props;
// use PubSub API
}
render() {
return (
<div>Connected Component</div>
);
}
}
ConnectedComponent.propTypes = {
pubSub: subscriptionShape.isRequired,
};
export default createPubSubConnector()(ConnectedComponent);
Attention createPubSubConnector
must be invoked twice, first with configuration parameters and the returned function with the component to be wrapped.
The PubSub Connector automatically remove all subscription when the component will unmount.
More info coming soon...
MIT