Last active
March 28, 2020 06:37
-
-
Save kcak11/87b3c263d5e0ea161c334a9200bc1a23 to your computer and use it in GitHub Desktop.
React Component PubSub Example
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</h1> | |
<div id="myapp"></div> |
This pen showcases an example of communicating between Vanilla JS & React Components using PubSub pattern.
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 { 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); |
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