Is there a way to make a leaflet popup responsive using react-leaflet library?

Viewed 1622
1 Answers

Install the library, import js, css get a map reference and then render the marker:

import R from "leaflet-responsive-popup";
import "leaflet-responsive-popup/leaflet.responsive.popup.css";
...
  const position = [51.505, -0.09];
  const mapRef = useRef();

  const icon = L.icon({
    iconUrl: "https://unpkg.com/leaflet@1.6/dist/images/marker-icon.png",
    shadowUrl: "https://unpkg.com/leaflet@1.5.0/dist/images/marker-shadow.png"
  });

  useEffect(() => {
    const map = mapRef.current.leafletElement;
    const marker = L.marker([51.5, -0.09], { icon });
    const popup = R.responsivePopup({
      hasTip: true,
      autoPan: true,
      offset: [15, 20]
    }).setContent("A pretty CSS3 responsive popup.<br> Easily customizable.");

    marker.addTo(map).bindPopup(popup);
  }, []);

  return (
    <Map center={position} ref={mapRef} zoom={13} style={{ height: "100vh" }}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
    </Map>
  );

Edit To have the plugin independent in an external wrapper component you can have a ResponsivePopup wrapper file:

const ResponsivePopup = () => {
  const { map } = useLeaflet();
  console.log(map);

  useEffect(() => {
    const marker = L.marker([51.5, -0.09], { icon });
    const popup = R.responsivePopup({
      hasTip: true,
      autoPan: true,
      offset: [15, 20]
    }).setContent("A pretty CSS3 responsive popup.<br> Easily customizable.");

    marker.addTo(map).bindPopup(popup);
  }, []);
  return null;
};

in which this time you will get the map reference using the useLeaflet hook provided by react-leaflet library and then you act similarly with the first solution. This time your Map or App comp will become like this:

 <Map center={position} zoom={13} style={{ height: "100vh" }}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      // here use your custom wrapper for responsive popup
      <ResponsivePopup />
    </Map>

Demo

Related