Search code examples
javascriptreactjswebpackcreate-react-app

How to construct js object in React


I have some problems with React and Advertisement. Wanna use 'Coupang' Advertisement, but they support the script library only. I can add it to 'index.html' in the public directory, but cannot customize the location.

here is the code,

<script src="https://ads-partners.coupang.com/g.js"></script>
<script>
    new PartnersCoupang.G({"id":23232,"subId":null});
</script>

It's a dynamic advertisement. How can I add it to the React functional component??


Solution

  • MB this will be helpful.

    useScript will help you add script to your code dynamically.

    and you custom hook (just create PartnersCoupang);

    const usePartnersCoupang = () => {
      const const [loaded, error] = useScript('https://ads-partners.coupang.com/g.js');
    
      React.useEffect(() => {
        if (loaded) {
          new PartnersCoupang.G({"id":23232,"subId":null});
        }
      }, [loaded]);
    
      React.useEffect(() => {
        if (error) {
          console.error('PartnersCoupang Failed.');
        }
      }, [error]);
    }