I am developing a React app on my Ubuntu 20.4 VM machine in a chrome Version 100.0.4896.127 (Official Build) (64-bit) browser.
I have created the following app:
https://codesandbox.io/s/react-leaflet-map-with-marker-forked-vtq00e?file=/Map.js
I am trying to set a marker when clicking on the map using the following:
In my Map.js I set the click event:
return (
<div id="map" style={style}>
<MapContainer
// center={[40.0151, -105.2921]}
center={[40.7579747, -73.9877313]}
// @ts-ignore
onClick={addMarker}
zoom={15}
style={{ height: "90%" }}
// @ts-ignore
onZoomEnd={console.log}
>
The following function should then set the marker:
function addMarker(e) {
console.log("marker \n");
const { markers } = this.state;
markers.pop();
markers.push(e.latlng);
this.setState({ markers });
}
However, when I click on the map nothing is happening. I also do not get a console output.
Any suggestions what I am doing wrong?
I appreciate your replies!
There is a reason why TypeScript tells you that onClick and onZoomEnd props are not available on <MapContainer> component from React Leaflet: the latter was introduced in React Leaflet version 3, and map events should now be used through the useMapEvents hook, as you already have tried in some of your attempts as can be seen in your CodeSandbox.
What may not be obvious with the useMapEvents hook, is that it must be used in a custom component that will be a child (descendant) of your MapContainer. See e.g. Trying to apply zoom on click with react-leaflet
Furthermore, this.setState is typical of class-based React components, whereas in your CodeSandbox you use functional components. Note that hooks can only be used in functional React components.