Why I Can't use Leaflet Map on Nextjs even with Dynamic Import?

Viewed 49

Leaflet need global window object and as you know on SSR there is no window and it will return an error window is not definded

I searched a lot and the only way to use Leaflet it was to use nextjs dynamic import but i get nothing In my Page

It's been a day I'm searching the web how to solve this and NOTHING worked so far for me.

I Really need an answer for this

Why Map component won't Render?

Map.tsx

import { useState } from "react";
import { MapContainer, TileLayer, Marker, useMapEvents } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
import "leaflet-defaulticon-compatibility";

const Map = () => {
  const [position, setPosition] = useState<[number, number]>([51.505, 51.505]);

  // Add Marker on Map onClick
  function Mark() {
    const map = useMapEvents({
      click: ({ latlng }) => {
        setPosition([latlng.lat, latlng.lng]);
      },
    });
    return <Marker position={position} />;
  }

  return (
    <MapContainer
      center={[35.7219, 51.3347]}
      zoom={6}
      scrollWheelZoom={false}
      style={{ height: "50vh" }}
    >
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
      <Mark />
    </MapContainer>
  );
};

export default Map;

my dynamic import

import dynamic from "next/dynamic";
const AdPage = ({ ad }: AdPageProps): JSX.Element => {

  const MapWithNoSSR = dynamic(() => import("./NewAd/map"), {
    ssr: false,
  });

  return (
    <>
            <MapWithNoSSR />
    </>
  );
};

export default AdPage;
1 Answers

In my app I use separate index.ts file in the same folder as Map component to import map dynamically

index.ts

import dynamic from "next/dynamic";

export default dynamic(() => import("./Map"), { ssr: false });

and then use simple import where I need this map

import CustomMap from "../Map";
Related