I have embeddable react widget with webpack config, below is the script tag which will be embedded in the client side.
<script>
(function (w, d, s, o, f, js, fjs) {
w['simple-widget'] = o; w[o] = w[o] || function () { (w[o].q = w[o].q || []).push(arguments) };
js = d.createElement(s), fjs = d.getElementsByTagName(s)[0];
js.id = o; js.src = f; js.async = 1; fjs.parentNode.insertBefore(js, fjs);
}(window, document, 'script', 'w1', 'widget.js'));
w1('init', { targetElementId: 'simple-widget', message: "some string" });
</script>
How to capture
message: "some string"
and send it to react ?
Below is my code to apiHandle
function apiHandler(api, params) {
if (!api) throw Error("API method required");
api = api.toLowerCase();
let config = window[widgetConfigName];
switch (api) {
case "init":
config = Object.assign({}, config, params);
window[widgetConfigName] = config;
// get a reference to the created widget component so we can
// call methods as needed
widgetComponent = React.createRef();
ReactDOM.render(
<Widget ref={widgetComponent} />,
document.getElementById(config.targetElementId)
);
break;
case "message":
console.log("switch case message");
// Send the message to the current widget instance
widgetComponent.current.setMessage(params);
break;
default:
throw Error(`Method ${api} is not supported`);
}
}
Below is my react Wideget.js Component
class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
message: null,
};
}
render() {
console.log(this.state);
return (
<div className="main_container">
{message}
</div>
);
}
}
You can get the message property from the simple-widget element if it exists in your DOM elements.
class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
message: null,
};
}
componentDidMount() {
const widgetElement = document.getElementById('simple-widget');
this.setState({message: widgetEelement.message})
}
render() {
return (
<div className="main_container">
{message}
</div>
);
}
}
In the component did mount function, you can get the widget by its id and get the message property from it, then set this message to the state.