1

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?

m19v
  • 1,800
  • 4
  • 11
  • 26

1 Answers1

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>
Seth Lutske
  • 9,154
  • 5
  • 29
  • 78