Skip to content

Instantly share code, notes, and snippets.

@kcak11
Last active March 28, 2020 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kcak11/87b3c263d5e0ea161c334a9200bc1a23 to your computer and use it in GitHub Desktop.
Save kcak11/87b3c263d5e0ea161c334a9200bc1a23 to your computer and use it in GitHub Desktop.
React Component PubSub Example

React Component PubSub Example

(using ES6 classes)

<h1>React Component PubSub Example</h1>
<div id="myapp"></div>

React Component PubSub Example

This pen showcases an example of communicating between Vanilla JS & React Components using PubSub pattern.

A Pen by K.C.Ashish Kumar on CodePen.

License.

const { Component, Fragment } = React;
const Observable = function (fn) {
const __subscriber = function (arg) {
fn(arg);
};
return {
publish: function (val) {
__subscriber(val);
}
};
};
let subscriber;
class Sample extends Component {
constructor(props) {
super(props);
this.state = {};
this.handleStateChange = this.handleStateChange.bind(this);
subscriber = Observable(this.handleStateChange);
}
handleStateChange(val) {
this.setState({ data: val });
}
render() {
return (
<Fragment>
<div>Value: {this.state.data}</div>
<span>
The value being changed is passed from external JS code.
</span>
</Fragment>
);
}
}
ReactDOM.render(<Sample />, document.getElementById("myapp"));
/*
Communication from Vanilla JS to React Component
The below JS code is not part of the React, but can communicate with the React Component.
*/
let ctr = 1;
setInterval(function () {
subscriber.publish(ctr);
ctr++;
}, 200);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
body {
font-family: Verdana;
div {
font-size: 16px;
font-weight: bold;
}
span {
font-size: 11px;
font-weight: normal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment