I would like to know if it is possible to write a widget with React and distribute it as a CDN to integrate it into another application react?
The idea: I have several applications in writing with react and I would like to have a banner common to all applications without having to rewrite it in each of them. The goal is to facilitate the updates of this banner.
My widget named toolBar works perfectly when I do npm start.
I have build my toolBar and add the script generate in the folder build into an other app named myAppTest.
My toolBar work and the other app to. However, the css and toolBar images are not loaded properly when launching myAppTest.
What is the best way pleasure ?
If by "integrating a widget with a react application" you mean a stand-alone react application (your widget) that needs to get data and pass data back to another application (react application in your case) then it's totally doable.
I even posted an article with a tutorial on how to do just that.
Basically the gist of it is that most of us learned that each react
application has an entry point that run this line:
ReactDOM.render(<App/>, myContainer);
As in fire and forget approach.
But actually we can run ReactDOM.render
as much as we want, it won't re-mount our application but instead will trigger the diffing for the tree.
If the React element was previously rendered into container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element.
So what we can do is wrap it in a function and expose it globally so other code on the page can run it.
A pattern i use is to accept props with that function and it will pass it on to the <App/>
via ReactDOM.render
.
For example:
window.CoolWidget = {
mount: (props, container) => {
ReactDOM.render(<CoolWidget {...props} />, container);
},
unmount: (container) => {
ReactDOM.unmountComponentAtNode(container);
}
}
And the consumers of your widget can run it:
window.CoolWidget.mount({widgetProp: someValue, onLogin: function(){...}}, myContainer)
The best thing with this approach is that they can convert this code to a react component (or maybe even you can do it for them!):
class CoolWidgetWrapper extends PureComponent {
// create a ref so we can pass the element to mount and unmount
widgetRef = React.createRef();
componentDidMount() {
// initial render with props
window.CoolWidget.mount(this.props, this.widgetRef.current);
}
componentDidUpdate(prevProps) {
if(prevProps !== this.props){
window.CoolWidget.mount(this.props, this.widgetRef.current);
}
}
componentWillUnmount(){
window.CoolWidget.unmount(this.widgetRef.current);
}
render() {
return <div ref={this.widgetRef}></div>
}
}
And this is how they will use it:
<CoolWidgetWrapper someProp={someValue} onLogin={someFunc} />
Hope that helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With