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

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...

Material UI and Next JS do not cooperate well with styles

Help! The global styles are taking over my custom ones. I'm working with Material UI in Next.js. ...

Conduct a JMeter stress test on a Next.js application to push the limits of available ports

I am completely new to stress testing, just letting you know. A bit of background information about the project, not the question itself: I have a web app built in nextjs14. A client has requested that it be able to support 400-500 simultaneous users conn ...

Custom container width causes animation to crash when scrolling

I'm having trouble with my header. When the containers change with scrolling, an animation takes place. Everything works fine with native Bootstrap CSS, but when I customize the width of the container in my custom CSS (the width set to 1140px), the an ...

Having trouble implementing the ternary operator (?) in TypeScript within a Next.js project

Trying to implement a ternary operator condition within my onClick event in a Next.js application. However, encountering an error indicating that the condition is not returning any value. Seeking assistance with resolving this issue... https://i.stack.img ...

Drawer in Material-UI has whitespace remaining at the corners due to its rounded edges

While using the Material UI drawer, I attempted to round the corners using CSS: style={{ borderRadius: "25px", backgroundColor: "red", overflow: "hidden", padding: "300px" }} Although it somewhat works, the corners appear white instea ...

Struggling to navigate a nested JSON API using NEXTJS?

I am facing difficulties while trying to extract nested JSON API data in NEXTJS. Specifically, I am struggling with extracting a dictionary within a dictionary from the API file. In the example provided below, I have only been successful in consuming entr ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

When attempting to implement styled-components in Next.js, there is an issue with the node module in React.js causing an error

I am trying to incorporate styled-components in my next.js react project. This is the approach I am taking: import styled from 'styled-components'; export const MainTitleContainer = styled.div` text-align:right; margin:3rem 0; paddin ...

Connecting to deeply nested attributes within an object using specified criteria

I apologize if the title of my query is not very descriptive, I couldn't come up with a better one. Please feel free to suggest improvements. I am currently working on developing a reusable "property grid" in Angular. My goal is to create a grid wher ...

Tips for continuing code execution in an ajax success function following the completion of a nested ajax call within the success block

I am facing an issue with a function that utilizes $.ajax. In the success section of the function, I have three nested functions. The first one executes properly, but the second one contains another $.ajax call. While the internal $.ajax call works fine, t ...

The Ionic project compilation was unsuccessful

Issue: This module is defined using 'export =', and can only be utilized with a default import if the 'allowSyntheticDefaultImports' flag is enabled. Error found in the file: 1 import FormData from "form-data"; ~~~~~~~~ node ...

Using parseFloat in JavaScript for German number formatting

Currently, I am working on incorporating a Vue.js component that is inspired by the example provided in this link: https://jsfiddle.net/mani04/bgzhw68m/. This is the structure of my source code: computed: { displayValue: { get ...

Having trouble uploading several files with Multer functionality?

I've encountered an issue with Multer in Node.js where I can't seem to select and upload multiple files. In a previous exercise, I had no trouble uploading a single file, but now I'm struggling with enabling multiple uploads. What am I mis ...

Increasing values in Mongoose using $inc can be done by following these steps

I've been struggling to increment a field value using $inc in my code. My schema looks like this: var postSchema = mongoose.Schema({ title : { type: String, required: true }, body : { type: String, default: '' }, coun ...

Tracing Bugs in a Next.js Application Using Visual Studio Code within an NX Monorepository

Currently tackling the task of debugging a Next.js Application within an NX monorepo. I have gone ahead and enabled the Auto Attach setting in the User Settings of my VSCode. Upon starting the Application using the serve command, I am able to view output ...

Here is a list of selections that can be easily removed and have a child selection added

While this question may be a bit ambiguous, please bear with me as I explain my dilemma. I am utilizing React to develop a component that accepts an object with keys and values as a prop. Each value within the object is a list of values. This component ne ...

Vuetify - Best practices for vertically aligning rows in a v-treeview component

Just getting started with Vue js, so pardon me if this is a silly question. I've scoured the internet and can't seem to find a solution. I'm working on a v-treeview displaying a folder structure, with descriptions of each folder in a separa ...

Displaying two different dates in AngularJS without any repetition of the similar elements

How can I elegantly display a date range that includes two dates, without repeating information if it's the same for both dates? My idea is something like this: Tue, 05 May 2015 19:31-20:31 GMT Mon, 04 19:31 - Tue, 05 20:31 May 2015 It's accept ...