Skip to content

Instantly share code, notes, and snippets.

@kcak11
Last active March 28, 2020 06:32
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/954ba3380a516240dfad989f7af09b6f to your computer and use it in GitHub Desktop.
Save kcak11/954ba3380a516240dfad989f7af09b6f to your computer and use it in GitHub Desktop.
React Component PubSub Example (using React Hooks)

React Component PubSub Example

(using React Hooks)

<h1>React Component PubSub Example (using React Hooks)</h1>
<div id="myapp"></div>

React Component PubSub Example (using React Hooks)

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

This specific example uses the "React Hooks" instead of the regular ES6 classes.

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

License.

const { Fragment, useState, useCallback } = React;
const Observable = function (fn) {
const __subscriber = function (arg) {
fn(arg);
};
return {
publish: function (val) {
__subscriber(val);
}
};
};
let subscriber;
const Sample = function (props) {
const [data, setData] = useState(null);
const handleStateChange = useCallback(function (val) {
setData(val);
});
subscriber = Observable(handleStateChange);
return (
<Fragment>
<div>Value: {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