I'm working on an SDK. It currently supports JavaScript however it needs to support React (& possibly Vue/Angular down the road).
It first loads the SDK via a script. Then modifies an element with the sdk-id. The user interacts with the element and the SDK fires a callback, AppNameSDK.callback(data). This all works fine on vanilla javascript however for React I'm having trouble figuring out how to call a callback within the React Component.
In short. How can I either A) Call a React Components function/method from an externally loaded Object or B) Change an externally loaded objects function via a React Component
Example of Vanilla Code (no problems)
<div
id="sdk-id"
data-foo="foo"
data-bar="bar">
</div>
<script src="https://example.com/sdk/v1/client-id"></script>
// Loads obj called AppNameSDK
<script type="text/javascript">
AppNameSDK.callback = (data) => {
console.log("data",data)
}
</script>
Example of React Code (cannot access callback)
import React,{useEffect} from 'react';
const useScript = (url,loadFunc,errorFunc) => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
script.addEventListener('load', function () {
if(loadFunc !== undefined && typeof loadFunc === "function"){
loadFunc();
}
});
script.addEventListener('error', function (e) {
console.log();
if(errorFunc !== undefined && typeof errorFunc === "function"){
errorFunc();
}
});
return () => {
if(document.body.contains(script)){
document.body.removeChild(script);
}
}
}, [url,loadFunc,errorFunc]);
};
const Test = () => {
let scriptSrc = "https://example.com/sdk/v1/client-id";
useScript(scriptSrc);
// Need to figure out how to call this function
const callback = (data) => {
console.log("data",data);
}
return (
<div className="test">
<h3>Test Component</h3>
<div
id="sdk-id"
data-foo={"foo"}
data-bar={"bar"}>
</div>
</div>
);
};
export default Test;