'react leaflet mouseover / hover popup

Hej!

I want my popup to open via a hover/mouseover.

I tried the recommended but it still only opens on click. Does anyone have an idea what is missing?

Any help is appreciated!

import React from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import L from 'leaflet';

const Map = () => {
    const renderIcons = () => {
    return(
        <Marker
         position = {[latitude, longitude]}
         icon     = {getIcon(markerType)}
         onMouseOver = {event => event.target.openPopup()}
        >
            <Popup>
             Hello 
            </Popup>
        </Marker>
     );
});
return(
    <MapContainer ...>
       <TileLayer .../>
       {renderIcons()}
    </MapContainer>
 );
}


Solution 1:[1]

You need to create a custom component and then one way would be to use eventHandlers to handle mouseover and mouseout events in combination with the marker ref to call leaflet's native openPopup and closePopup methods respectively.

const RenderIcons = () => {
  const markerRef = useRef();

  const eventHandlers = useMemo(
    () => ({
      mouseover() {
        if (markerRef) markerRef.current.openPopup();
      },
      mouseout() {
        if (markerRef) markerRef.current.closePopup();
      }
    }),
    []
  );

  return (
    <Marker
      ref={markerRef}
      position={position}
      icon={icon}
      eventHandlers={eventHandlers}
    >
      <Popup>Hello</Popup>
    </Marker>
  );
}; 

Demo

Solution 2:[2]

It can be done without useMemo and useRef however still using eventHandlers:


<Marker
  position={[latitude, longitude]}
  icon={getIcon(markerType)}
  eventHandlers={{
    mouseover: (event) => event.target.openPopup(),
  }}
>
  <Popup>Hello</Popup>
</Marker>;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kboul
Solution 2 Disco