Skip to content

Instantly share code, notes, and snippets.

@bhargavkakadiya
Created January 28, 2024 07:36
Show Gist options
  • Save bhargavkakadiya/2d33ec8623cc43b8b693ed0838534db8 to your computer and use it in GitHub Desktop.
Save bhargavkakadiya/2d33ec8623cc43b8b693ed0838534db8 to your computer and use it in GitHub Desktop.
React Leaflet Integration in Next.js

Implementing Dynamic Map Component

Use Next.js's dynamic function to import the Map component dynamically. This ensures it's only rendered on the client side.

Implement this if you have encountered window not defined error and if nextjs build fails

import dynamic from "next/dynamic";
const DynamicMap = dynamic(() => import("./Map"), {
  loading: () => <p>Loading...</p>,
});

export default function App() {
  return (
    <>
      <DynamicMap />
    </>
  );
}
import React from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';

const Map = () => {
  const position = [51.505, -0.09]; // Example position: London

  return (
    <MapContainer center={position} zoom={13} style={{ height: '400px', width: '100%' }}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      />
      <Marker position={position}>
        <Popup>
          A simple popup. <br /> Easily customizable.
        </Popup>
      </Marker>
    </MapContainer>
  );
};

export default Map;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment