Stumble upon in the search of adding Buy me coffee script into react application land to the following wonderful hook solution to add script to react on stack overflow here
I will also add up here the update code of stack overflow which helped in the solution (for incase above shared link will be changed in future, and all the code credit is to the author of stack overflow user)
Update:
Now that we have hooks, a better approach might be to use useEffect like so:
useEffect(() => {
const script = document.createElement('script');
script.src = "https://use.typekit.net/foobar.js";
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, []);
Which makes it a great candidate for a custom hook (eg: hooks/useScript.js):
import { useEffect } from 'react';
const useScript = url => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, [url]);
};
export default useScript;
Which can be used like so:
import useScript from 'hooks/useScript';
const MyComponent = props => {
useScript('https://use.typekit.net/foobar.js');
// rest of your component
}
Solution, I have added on top a ‘config’ param to the useScript function for easy BMC Buy me coffee widget attributes to get added to script object dynamically:
const useScript = (url, config = null) => {
useEffect(() => {
const script = document.createElement("script");
script.src = url;
script.async = true;
if (config && Object.keys(config).length) {
for (let key in config) {
script.setAttribute(key, config[key]);
}
}
// console.log(script);
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [url]);
};
export default useScript;
Boom!