Mappy / Leaflet-active-area

A Leaflet plugin to center the map not in the center of the map but inside a DIV. Useful for responsive design.

Home Page:https://mappy.github.io/Leaflet-active-area/examples/index.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

react integration

mrafei opened this issue · comments

Hi,
Any plans to release an integration with react-leaflet?

Thanks

Hello,

That’s a good idea indeed.

However, we do not have any plan to integrate leaflet-active-area with react-leaflet in a near future.

Regards

Hi, little late to the party, but if you still wanna use it in React, it can be used like this. (Working on my NextJS 14.x and react-leaflet 4.2.1)

You can install it npmjs.com or copy it from this repo.

"use client";

import { MapContainer, GeoJSON, useMap } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-active-area";

const MapContent = () => {
  const map = useMap();

  useEffect(() => {
    map?.setActiveArea("activeArea", true, true);
  }, [map]);

  return (
    <GeoJSON  />
  );
};

export default function Map() {
  return (
      <MapContainer>
        <MapContent />
      </MapContainer>
  );
}

leaflet-active-area will render empty <div class="activeArea"></div> so you can somewhere in css define .activeArea class like this (I will use tailwind here)

@layer components {
  .activeArea {
    @apply absolute top-0 bottom-32 right-0 left-0 border border-primary;
  }
}

I tore apart this example from my complex code, so thiswill not work by copy/paste, I think.

Hi @benistary this was a great solution! I am having a little trouble as a beginner... did you also struggle with the error:
`Cannot read properties of null (reading 'getBounds')
TypeError: Cannot read properties of null (reading 'getBounds')
at NewClass._onZoomEnd (http://localhost:3004/static/js/bundle.js:23342:40) ... and four more?

something is obviously going on when I added this function, but I am clueless and nooby as to what this means/where to start triaging.

@benistary As I try to figure it out, could you maybe say a word about why the MapContent is needed here? is there a way to do it simply on MapContainer?

It is because you can use useMap() hook only inside MapContainer's context. So it has to be used directly inside some child component. Then you have access to map instance, like it is in my example.

Sorry, but I do not know why you have got error mentioned in your first question. But let us know please if you will resolve it. :)