0

In react-leaflet, I am trying to add a draggable button to the map as shown in the image below. I also want the rest of the div to be non-clickable.

Project screenshot

However, when I click the button, nothing happens.

I want it so that when I click the button, the handleClick function is fired.

Below is the code for the project.

IconWithButton.js

import { MapContainer, TileLayer, Marker } from "react-leaflet";
import { divIcon, Point } from "leaflet";
import { renderToString } from "react-dom/server";
import "leaflet/dist/leaflet.css";

function handleClick() {
  alert("Button Clicked!");
}

function ExampleIcon() {
  return (
    <div style={{ backgroundColor: "green" }}>
      <h1>Non-clickable text</h1>
      <button onClick={handleClick}>Clickable Button</button>
    </div>
  );
}

const customIcon = divIcon({
  html: renderToString(<ExampleIcon />),
  className: "",
  iconSize: new Point(250, 250),
});

function IconWithButton() {
  return (
    <div style={{ height: "1000px" }}>
      <MapContainer
        center={[51.505, -0.09]}
        zoom={13}
        scrollWheelZoom={true}
        style={{ height: "100%" }}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={[51.505, -0.09]} icon={customIcon} draggable={true} />
      </MapContainer>
    </div>
  );
}
export default IconWithButton;

Codesandbox https://codesandbox.io/p/sandbox/react-leaflet-button-icon-mtxpl5?file=%2Fsrc%2FIconWithButton.js%3A10%2C25

1 Answer 1

0

Rather than adding the click handler to the button, you can use the click event in the eventHandlers prop of the <Marker>. In the click event handler function you can inspect the HTML element the event originated from (i.e the thing the user clicked on) and only perform an action if it was the button:

<Marker
  ...
  eventHandlers={{
    click: (e) => {
      if (e.originalEvent.target.id === "myButton") {
        alert("x");
      }
    },
  }}
/>

To make this work you will need to give your button an ID so you can determine whether the click was made on the button or not:

<button id="myButton">Clickable Button</button>

There's a Code Sandbox thay shows this approach working.

Not the answer you're looking for? Browse other questions tagged or ask your own question.