Warm tip: This article is reproduced from serverfault.com, please click

React Leaflet: Custom event "onClick" for Marker component

发布于 2020-11-30 15:41:58

I want to define a react component for Marker element of 'react-leaflet'. E.g.

import React,{useState} from 'react'
import {Marker,useMapEvent } from 'react-leaflet'
import fireIconSvg from './fire-icon.svg'

import L from "leaflet";

const OSLocationMarker = ( {position, onClick} ) => {

  const locationIcon = new L.Icon({
    iconUrl: fireIconSvg,
    iconRetinaUrl: fireIconSvg,
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(35, 45),
    className: 'location-icon'
});

return (
      <Marker
        data="customdata"
        position={position}
        icon={locationIcon}
        onClick={onClick}
      >
      </Marker>
  );
}

export default OSLocationMarker;

By this I want to trigger a function when one click on any OSLocationMarker (there are N markers). OSLocationMarker get the callback function as prop. This does not work. With useMapEvent() leaflet hook i did not get it working. Why is the function not being called?

Questioner
1c0DevPi
Viewed
0
Seth Lutske 2020-12-01 00:24:11

onClick doesn't work anymore in react-leaflet v3. useMapEvent(s) applies to the map instance, not to UI components like Marker. To register an event handler on a Marker, you need to use the eventHandlers prop:

<Marker
  data="customdata"
  position={position}
  icon={locationIcon}
  eventHandlers={click: onClick}
>
</Marker>