Notification texts go here Contact Us Buy Now!

Render React component as a custom marker icon in react-leaflet with working events/interaction

To address the issue with onClick event not working and have interactive React components as custom marker icons in react-leaflet, here's a step-by-step solution:

  1. Utilize L.divIcon: Create a placeholder div as the icon, which initially contains nothing. Assign a unique ID to this div for each marker.
  2. Leverage Marker's add Event: Use the Marker component's add event to detect when the icon has been rendered into the DOM.
  3. React Portal Integration: Once the icon is rendered, employ a React portal to render the actual React component within the placeholder div. Target the div using the unique ID.
  4. Handle Marker Removal: Additionally, detect when the marker is removed and subsequently remove the portal.

To simplify this process, we can encapsulate this behavior in an EnhancedMarker component:

import React, { useState, useId, useMemo } from "react";
import { createPortal } from "react-dom";
import { MapContainer, TileLayer, Marker } from "react-leaflet";

const EnhancedMarker = ({
  eventHandlers,
  icon: providedIcon,
  ...otherProps
}) => {
  const [markerRendered, setMarkerRendered] = useState(false);
  const id = "marker-" + useId();

  const icon = useMemo(
    () =>
      L.divIcon({
        html: `
`, }), [id] ); return ( <> { setMarkerRendered(true); if (eventHandlers?.add) eventHandlers.add(...args); }, remove: (...args) => { setMarkerRendered(false); if (eventHandlers?.remove) eventHandlers.remove(...args); }, }} icon={icon} /> {markerRendered && createPortal(providedIcon, document.getElementById(id))} ); }; const MarkerIconExample = () => { return ( <> ); }; const CENTER = [51.505, -0.091]; const ZOOM = 13; const App = () => { return ( } /> ); };

For your specific use case, you can:

  1. Copy and incorporate the EnhancedMarker component into your code.
  2. Replace instances of <Marker> with <EnhancedMarker>.
  3. Utilize <IconGen /> within the icon prop of <EnhancedMarker>.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.