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.
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='© <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