I am currently looking to integrate Shopify with my personal website.
My frontend is built using React (NextJS with TypeScript). The embed code for the Shopify buy button consists of an HTML div tag wrapping JavaScript. I am wondering how I can effectively incorporate this code into my .tsx file to display it on my frontend?
Code: Below is the code provided by Shopify to embed the Buy Button on a .html page, which includes HTML and JS:
<div id='collection-component-XXXXXXXXXX9'></div>
<script type="text/javascript">
/*<![CDATA[*/
(function () {
var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';
if (window.ShopifyBuy) {
if (window.ShopifyBuy.UI) {
ShopifyBuyInit();
} else {
loadScript();
}
} else {
loadScript();
}
function loadScript() {
var script = document.createElement('script');
script.async = true;
script.src = scriptURL;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
script.onload = ShopifyBuyInit;
}
function ShopifyBuyInit() {
var client = ShopifyBuy.buildClient({
domain: 'xxxxxxxxxxx.myshopify.com',
storefrontAccessToken: 'xxxxxxxxxxxxxxxxxxxxxx',
});
ShopifyBuy.UI.onReady(client).then(function (ui) {
ui.createComponent('collection', {
id: 'xxxxxxxxxxxxx',
node: document.getElementById('collection-component-XXXXXXXXXXX9'),
moneyFormat: '%24%7B%7Bamount%7D%7D',
options: {
"product": {
// Styles properties
},
"productSet": {
// Products styles
},
"modalProduct": {
// Modal product contents and styles
},
"option": {},
"cart": {
// Cart styles
},
"toggle": {
// Toggle styles
}
},
});
});
}
})();
/*]]>*/
</script>