Tips for transferring a variable from Next.js to a plain JavaScript file

When it comes to Canvas Dom operations in my NextJs file, I decided to include a Vanilla JS file using 'next/script'. The code for this is:

<Script id="canvasJS" src="/lib/canvas.js" ></Script>
. Everything seems to be working fine at the moment. However, I now face the challenge of passing a variable (like an ID) from the NextJs file to the Vanilla File without any user interaction. While I have managed to make it work with onClick using ()=>functionName(value), the process of passing a value without user interaction still puzzles me. If anyone has some insight or advice on how to achieve this, I would greatly appreciate it. Thank you in advance, Frank

Answer №1

If you want a simple way to access the hydrated props coming from the server in your vanilla JavaScript script, just read

window.__NEXT_DATA__.props.pageProps
.

Alternatively, you can try something like this:

import { useLayoutEffect } from 'React';
import Script from 'next/script';

export default function Component() {

  useLayoutEffect(() => {
   // Perform actions with variables and external scripts here
  },[]);

  return (
    <>
      <Script src="/lib/canvas.js"/>
    </>
  )
}

If you're unsure about what exactly canvas.js does, consider using the useLayoutEffect hook. This will ensure that your code runs after the script has been loaded and browser's DOM has been updated.

For more information on next/script, check out the documentation page at: https://nextjs.org/docs/basic-features/script

Answer №2

One approach I like to take is utilizing local storage.

In my scenario, I utilize a getServerSideProps(ctx) function to check for a board ID in the URL. If no ID is found, I generate a unique one.

I then pass on the props. On the client side, I extract the bid from the props and store it in local storage:

Next.js

if (typeof window !== "undefined") 
{
  localStorage.setItem('bid', bid) ;  
}

Later, in a separate vanilla JS file, I retrieve the ID using:

Vanilla JS

const bid = localStorage.getItem('bid');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can be taken to revert this Node.js module to a particular version and ensure it does not automatically update in

While using the Nodemailer module in node.js, I encountered a specific error that read as follows; [Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 or see the migration guide https://github.com/andris9/Nodemailer#migration-guide] A ...

Running NPM module via Cordova

After developing an app using cordova, I encountered a challenge where I needed to incorporate a node module that lacked a client-side equivalent due to file write stream requirements. My solution involved utilizing Cordova hooks by implementing an app_run ...

Transferring JavaScript files via Node server using NowJS

As someone new to Node, I need some help with a server-client web application I'm creating for a board game using Raphael for graphics. The issue I'm facing is that while the server successfully sends the HTML file in response to requests, the b ...

The entire Sphere Geometry in three.js is not completely encompassed by the texture

Click here to view the image I'm trying to create a rotating moon. Everything works perfectly with MeshStandardMaterial (with color but no texture), however, when I apply a texture to the sphere geometry, it behaves strangely. The issue I'm facin ...

Tips for populating an HTML input with the value of a link element using JQuery

I have a form input that I want to populate with autocomplete suggestions from my database using Ajax. To style the list, I am using bootstrap 4, and I have opted to use the <a></a> tag instead of the <li></li> tag. This is because ...

JavaScript Class experiencing issues with returning NAN when using the Multiplication method

Currently, I have a JavaScript Class with a multiplication method that aims to multiply all elements of an array excluding those that are undefined. To achieve this, I utilized a for loop to check the data type of each element (ensuring it is a number) and ...

What causes the first button to be clicked and the form to be submitted when the enter key is pressed within a text

Start by opening the javascript console, then place your cursor in the text box and hit enter. What is the reason for the function "baz" being called? How can this behavior be prevented? function foo() { console.log('foo'); } function bar() ...

Incorporating React components into your current Django project

My goal is to enhance the interactivity of a specific part of my Django website by incorporating React components into the template HTML file. Instead of replacing the entire template with React, I want to focus on integrating React for its ease in handlin ...

Utilizing a function as an argument in another function (with specified parameters)

I’m stuck and can’t seem to solve this problem. In my function, the parameter filter needs to be a function call that accepts an object created within the same function: function bindSlider(time, filter) { var values = { min : 8, max : ...

Using the power of jQuery, execute a function only once when the element is clicked

My goal is to use jQuery's .one method to change the color of an element only once, even if clicked again. However, I am having trouble getting it to work properly. Here is my HTML: <!DOCTYPE html> <head> <meta charset="UTF-8"& ...

How to deactivate the <a> tag with Ant Design UI Library

Is there a method in the antd UI library to disable a link? The disabled attribute is not supported by the a tag according to MDN. This code snippet works in React but the link remains clickable when using Next.js. <Tooltip title={tooltip}> <a ...

Include the distribution file from the npm package in the final build

Working on my react-based project, I've integrated the node-poweredup npm package to enhance functionality. This useful library comes in both a nodejs and browser version. To include the browser version in my app, I simply link the script located at j ...

JavaScript obtain scroll position of a child element

I have a setup that looks something like the following: <div> <div id="scrollID" style="height:100px;"> content here </div> </div> <script> document.getElementById("myDIV").addEventListener("touchstart", m ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

How can I use jQuery to automatically redirect to a different HTML page after updating a dynamic label?

When I click on a button in first.html, a function is called to update labels in second.html. However, despite being able to see second.html, I am unable to see the updated values in the labels. Can someone please advise me on how to achieve this? functi ...

Preserve the ajax controls while uploading files

I encountered a minor issue with file uploading. When I click the upload button, a window (ajax powered) pops up for selecting a file. However, as soon as the file is uploaded to the browser, the page reloads and the window closes, leaving me without the ...

Is there a comparable Javascript alternative to the Ruby gem "site_prism" for Page Objects design?

Is there a JavaScript framework for Protractor in NodeJS that provides a clean way to define Page Object Elements similar to site_prism? I've explored astrolabe but it doesn't quite meet the requirements. This is an example of how Page Objects a ...

The issue I'm facing with Angular 8 is that while the this.router.navigate() method successfully changes the URL

As someone who is relatively new to Angular, I am currently in the process of setting up the front end of a project using Angular 8. The ultimate goal is to utilize REST API's to display data. At this point, I have developed 2 custom components. Logi ...

Having trouble getting the JavaScript slider to animate

My code works perfectly in Codepen but when I try to implement it on my website, it shows as a static image. You can view the code here: https://codepen.io/anon/pen/zPMKpv I'm using the exact same code on my website located at: Does anyone have any ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...