Last active
March 28, 2020 06:32
-
-
Save kcak11/954ba3380a516240dfad989f7af09b6f to your computer and use it in GitHub Desktop.
React Component PubSub Example (using React Hooks)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>React Component PubSub Example (using React Hooks)</h1> | |
<div id="myapp"></div> |
A Pen by K.C.Ashish Kumar on CodePen.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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