Search code examples
typescriptleafletreact-leaflet

Adding onClick attribute to Leaflet marker


I am trying to generate a list of points in Leaflet by looping through a JSON file and making each of them clickable in a way so I can get the active point into my react state.

I found this nice example that worked perfectly:

https://www.bekk.christmas/post/2020/13/a-hot-chocolate-map-with-react-leaflet-and-typescript for displaying the points, but in addition, I would like to set a react state based on which one the user has clicked.

When I try adding the onClick attribute:

import { Popup, Marker } from "react-leaflet";
import { list } from "./HotChocolate";
...

  {list.map((item, index) => (
    <Marker
      icon={icon2}
      key={index}
      position={[item.lat, item.lon]}
      title={`${item.englishProductName} at ${item.vendor}`}
      onClick={() => {
        console.log(item);
        console.log("do something more");
      }}
    >
      <Popup>
        <strong>
          {item.englishProductName} at {item.vendor}
        </strong>
      </Popup>
    </Marker>
  ))}

I get the following error:

Type '{ children: Element; icon: Icon<{ iconUrl: string; iconSize: [number, number]; }>; key: number; position: [number, number]; title: string; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & MarkerProps & RefAttributes<Marker>'.
Property 'onClick' does not exist on type 'IntrinsicAttributes & MarkerProps & RefAttributes<Marker>'

The other files are:

import { type HotChocolate } from "../../../leaflet";

export const list: HotChocolate[] = [
  {
    productName: "Varm belgisk sjokolade",
    englishProductName: "Belgian hot chocolate",
    vendor: "Steam kaffebar",
    location: "Jernbanetorget 1, Østbanehallen",
    lat: 59.91088362120013,
    lon: 10.752799203777597,
  },
  ...
];

And the type definitions are:

export interface HotChocolate {
  productName: string;
  englishProductName: string;
  vendor: string;
  location: string;
  lat: number;
  lon: number;
  description?: string;
  //onClick: () => void;
  //onClick: React.MouseEventHandler<HtmlInputElement>;
}

I assume I should be adding an onClick type definition to the leaflet.d.ts file above, but I am struggling to get the type correct. Does anyone have any advice on how I could make the different points in the HotChocolate list clickable in a way to I can set a react state based on which item the user has clicked on?


Solution

  • As @strfx was pointing out in the comments, the solution was to add the eventHandlers prop instead of onClick and then everything worked out perfectly.