Tech

How to add Buy me coffee script dynamically into React application or Javascript

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!

admin

Recent Posts

The Ultimate Guide to Effective Meetings

In today’s fast-paced work environment, meetings are essential but can often feel unproductive. However, by…

2 months ago

From Mine to Market: How Gold Is Mined, Refined, and Sold in Shops

Gold is one of the most coveted precious metals in the world, adored for its…

3 months ago

The Historical Journey of Gold: From Ancient Civilizations to Modern Times

Gold, the shimmering metal synonymous with wealth, power, and beauty, has been deeply intertwined with…

3 months ago

How to Onboard an Intern in Small, Individual-Based Company

How to Onboard an Intern in a Small, Individual-Based Company Hiring an intern can be…

4 months ago