Is there a way to trigger a function with the onclick event in NextJs?

Working on my NestJS project, I am still a beginner in the field. My current task involves creating a web application that displays a leaflet map with clickable tiles. Each tile should have a button that triggers a specific function when clicked. However, I seem to be facing issues with using the <button> tags and getting the onclick functionality to work properly. Is there an alternative approach to achieve this? Your insights are much appreciated!

Here is a snippet of my code:

const onEachSurface = (surface, layer) => {
  const textOnPopup =
    surface.properties.kachel + // This shows the number of the selected tile
    ' ' +
    `<button onclick = "addToCart()"
      class="bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border-gray-400 rounded shadow"
    >Add to cart</button>
    <script type="text/javascript">
      function addToCart() {
        console.log('hello my old friend');
      }
    </script>`;
  layer.bindPopup(textOnPopup);
};

The frontend view currently appears as shown in this screenshot.

Upon clicking a tile, the popup displaying the tile number appears correctly. However, the button fails to execute the designated function due to NextJs being unaware of it. The numeric value alongside the button corresponds to "surface.properties.kachel" in the code (which loads data from a background JSON file).

Answer №1

After revising my code, it looks like this:

const onEachSurface = (surface, layer) => {
const div = document.createElement('div');
const text = surface.properties.kachel;
const space = ' ';
const buttonAddToCart = document.createElement('button');
buttonAddToCart.innerHTML = 'add to cart';
buttonAddToCart.data = surface.properties.kachel;
buttonAddToCart.className =
  'bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border-gray-400 rounded shadow';
buttonAddToCart.onclick = function () {
  addToCart();
};
div.append(text);
div.append(space);
div.append(buttonAddToCart);

layer.bindPopup(div);};

Success! Everything is functioning now. Thanks once more Terry :)

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

Handling every promise in an array simultaneously

I am facing a problem with my array inside Promise.all. When I try to execute a function for the last iteration of forEach loop, I notice that my count_answers variable is only being set for the last object. This can be seen in the log output; the count_an ...

Modify the properties of a particular component

I have an array of rooms filled with data: const room = (<Room points={points} scene={this.scene} key={this.rooms.length} keyV={this.rooms.length} />) this.roomData.push(room); For example, I now have 3 rooms each with their ...

What is the best way to make three divs that can be adjusted in size?

Desired Layout: | A | | B | | C | ^ ^ Adjustment Behavior: | A | | B | | C | Current Issue: | A | C | I attempted to enhance the functionality by modifying the provided JavaScript cod ...

Expand the clickable area of the checkbox

Is it possible to make clicking on an empty space inside a table column (td) with checkboxes in it check or uncheck the checkbox? I am limited to using only that specific td, and cannot set event handlers to the surrounding tr or other tds. The functional ...

An issue arises in vue.js where the v class binding takes precedence over other bindings and fails to properly remove

I have a game with a punching bag where I want to incorporate an animation class each time the bag is clicked. Once the health meter hits zero, I intend to replace the bag image with one depicting a burst bag. Things are running smoothly up until the poin ...

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

Using getServerSideProps in Next.js is preventing the global css from loading

In my Next.js application, I have defined global styles in the file /styles/globals.css and imported them in _app.tsx. // import default style import "../styles/globals.css"; function MyApp({ Component, pageProps }) { return <Component {...pageProps ...

Transferring data between JavaScript and PHP

Is there a way to transfer data from JavaScript to PHP when a button is clicked? For instance, can the getdate() function's result be sent to PHP? This transferred value will then be utilized for database manipulation. ...

JavaScript module encounters an uncaught error: Attempting to assign a value to a constant variable

In another module, I defined a variable in the following manner: // module1.js let directory; export { directory }; Now, I am trying to access it in a separate module like so: // module2.js import { directory } from '../js/module1.js'; directo ...

"Troubleshooting IE-specific problem: Loading dropdown options dynamically with AJAX on change

Struggling with a particular issue lately. I'm attempting to populate a second dropdown menu based on the selection made in the first one using jquery ajax. Surprisingly, it works flawlessly on all browsers except for IE 11. Below is the ajax functio ...

Using JQuery to duplicate and assign individual IDs to each clone

Currently, I am in the process of developing a straightforward web application. Users will enter information by selecting options from drop-down menus and typing text into designated fields. Upon completion, users can click on a "generate" button that will ...

The searchBox from Algolia seems to be experiencing some technical difficulties and is not currently able to accept any new

Although I've implemented Algolia's SearchBox in my Next.js project, the input value remains unchanged when I attempt to type new values. I've replicated the boilerplate and integrated it multiple times with no success in updating the value. ...

Creating a timer implementation in Node.js using Socket.IO

In the process of developing a drawing and guessing game using node.js and socket.io, I have a structure consisting of a Room class, a Game class (which is an extension of Room), and a Round class where each game consists of 10 rounds. During each round, a ...

What exactly is the concept of lazily installing a dependency?

The website here contains information about the changes in Ember 2.11. Ember 2.11 now utilizes the ember-source module instead of the ember Bower package. In the upcoming Ember CLI 2.12 release, Bower will no longer be installed by default but will only ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Selecting an item with Material UI AutoComplete now automatically clears the value

After making a selection, I want to clear the value in the input field immediately. Currently, the value is cleared on blur but not upon selection. <Autocomplete disabled={showTextField} className="center-vertically" options={listOfDependencies ...

Utilizing Meteor.js with MongoDB to efficiently query proximity based on GeoJSON Point coordinates within a specific longitude range, enhanced by Leaflet.js

Using Meteor.js and Leaflet.js, I was able to successfully display limited markers around the $near query of a "2dsphere" indexed Collection. To accomplish this, I indexed my GeoJSON coordinates: Locations._ensureIndex({'geometry.coordinates':&a ...

How can you prevent the blur event from triggering in jQuery when the next element to receive focus is of a specific type?

I am currently developing a unique form UI where I am working on creating a custom select box replacement. The custom select control consists of a hidden select input within a div, along with anchor elements inside a span that mimic the options of the sele ...

What is the process for retrieving paginated data from the store or fetching new data from an API service within an Angular 2 application using ngrx-effects?

After coming across this insightful question and answer about the structure of paginated data in a redux store, I found myself pondering how to implement similar principles using ngrx/store in an angular 2 application. { entities: { users: { 1 ...

Is it possible to use a single function to both set the state and return JSX?

I'm currently grappling with creating a function that, when called, will update the state to an object {item: 'whatever the user types', list: [...list, todo]}. The challenge I'm facing is figuring out how to update the state and return ...