I feel like there should be a very simple solution to this and I can't seem to find one. I would like to embed code on my Next.js website, however, it will only work if I refresh the page. It does not load when I navigate to it via router/navbar link.
I tried to render it in useEffect() and useState(), however, the <script> doesn't seem to want to run in the useEffect() hook. I have not found a successful way to get dirty with it and use vanilla JavaScript in getServerSideProps() as suggested in another post, but I did find next/script in the documentation. This actually treats the script mostly how I need it to as far as when it renders. There is only one issue...
It does not render in the location I put it in the DOM. Instead it renders at the bottom of the webpage (even below the footer). I tried creating a component and then inserting it but that did not work either. This is because not only is it at the bottom of the current page, it's loading at the bottom of every page.
Any help is appreciated. Thank you!
Embedded component:
import Script from "next/script";
export default function paintCalculator() {
return (
<Script
async
type="text/javascript"
id="paint-calculator-tool"
data-type="dotdash-tool"
data-vertical="thespruce"
src="https://www.thespruce.com/static/5.174.0/static/components/widgets/iframe-embed/embed.min.js?id=paint-calculator-tool"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `!function(){var e,i,n,a,t=document.getElementsByTagName("script");[].forEach.call(t,function(t){"dotdash-tool"===t.getAttribute("data-type")&&(e=t.parentElement,i=document.createElement("iframe"),n=t.getAttribute("id"),a=t.getAttribute("data-vertical"),i.src="https://www."+a+".com/tools/"+n,i.style.border="none",i.id=n,i.style.width="100%",t.nextSibling&&t.nextSibling.id===n||e.insertBefore(i,t.nextSibling))}),window.addEventListener("message",function(e){var t=document.getElementsByTagName("iframe");[].forEach.call(t,function(t){t.getAttribute("id")===e.data.embedId&&(t.style.height=e.data.height+10+"px")})},!1)}();`,
}}
/>
);
}
Page with imported component:
import styles from "../styles/Home.module.css";
import React from "react";
import PaintCalculator from "../components/PaintCalculator";
export default function paintCalculator() {
return (
<div className={styles.pageContainer}>
<div>
<h1>Paint Calculator</h1>
<PaintCalculator />
</div>
</div>
);
}