Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

356
Vistas
How to pass a variable from nextjs to a vanilla js file?

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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');
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda