Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

285
Views
React-Leaflet: Set marker when clicking on the map

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!