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!
Break! I didn’t plan it. One day I just didn’t feel like opening Instagram—and then…
AI tools Let’s be real—AI sounds like either a robot apocalypse or something only tech…
Summer vacation is a great time for kids to explore, have fun, and learn new…
Goal: Understand transformers, large language models, and the architecture behind ChatGPT. Tutorial Suggestions: ✅ “Transformers…
Goal: Build apps or tools with ChatGPT or GPT-4 API. Tutorial Suggestions: ✅ OpenAI API…
Goal: Learn how to prompt better, write content, brainstorm, code, etc. Tutorial Suggestions: ✅ OpenAI's…