Home > OS >  How can I execute a function with onclick in NextJs?
How can I execute a function with onclick in NextJs?

Time:09-14

I am currently working on a NestJS-project, but I’m just a beginner. My Web-application should display a leaflet-map with clickable tiles. For each tile I want to display a button which when clicked fires a function. Unfortunately, the tags do not seem to work. How do I make the function work with onclick? Is there maybe another option to write this? Thank you so much in advance!

my code:

const onEachSurface = (surface, layer) => {
const textOnPopup =
  surface.properties.kachel   //here I display the number of the selected tile
  ' '  
  `<button onclick = "addToCart()" 
   >Add to cart</button>
  <script type="text/javascript">
    function addToCart() {
      console.log('hello my old friend');
    }
  </script>`;
layer.bindPopup(textOnPopup);};

on the front-end it looks like this: click here to see screenshot

here you can see the error message from NextJs. The current funtionality is that one can click on a tile and the popup with the tile-number appears. The button should execute a simple function, but NextJs does not know the function. The number next to the button is represented by "surface.properties.kachel" in the code (a JSON-file is loaded in the background)

CodePudding user response:

I changed my code to 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);};

Now it workes! Thanks again Terry :)

  • Related