for Canvas Dom operations I included a Vanilla JS file with 'next/script' into my NextJs file. <Script id="canvasJS" src="/lib/canvas.js" ></Script> That works fine so far.
Now I need to pass a variable like an ID from the NextJs file to the Vanilla File.
For onClick it works fine with ()=>functionName(value), but I have no idea how to pass a value without a user interaction.
It would be cool if someone could tell me how to do that.
thanks in advance Frank
The easiest approach is to read window.__NEXT_DATA__.props.pageProps on your vanilla js script. The object is the hydrated props that are coming from server and will be passed to your page component.
But if i were you i will use something like this.
import { useLayoutEffect } from 'React';
import Script from 'next/script';
export default function Component() {
useLayoutEffect(() => {
// do something you want to do with variable and external script
},[]);
return (
<>
<Script src="/lib/canvas.js"/>
</>
)
}
Not entirely sure about what is canvas.js does. Probably you could use something like this. The useLayoutEffect will run on the browser after DOM mutation, so the code inside useLayoutEffect will run after the script is loaded.
For more detail about next/script you can read this docs page.
https://nextjs.org/docs/basic-features/script
Ok, my way to do it, is to use local storage.
In my case I check the URL for a board ID in a getServerSideProps(ctx) function and if no ID is set I create a unique one.
Then I return the props. In the client side function I pick the bid from the props and write it to local storage:
Next.js
if (typeof window !== "undefined")
{
localStorage.setItem('bid', bid) ;
}
Then in the vanilla JS file I grab the ID by
Vanilla JS
const bid = localStorage.getItem('bid');