#Nextjs#Web-Development
Displaying a Leaflet Map in NextJS

Medium • Tomisin Abiodun
Jul 23
A crash course on using Leaflet Maps in NextJS

Originally published on my blog.
Installation
- First, install the leaflet library and its React wrapper with the following command:
npm install leaflet react-leaflet - (For TypeScript projects) Install the types for the leaflet library
npm install -D @types/leaflet - Install a library containing the default icons (icons might not display properly if this step is omitted)
npm install leaflet-defaulticon-compatibility
Usage
1. Define your Component
In a component outside the page where you wish to display the map, create and export a map component similar to this:
// src/components/Map.tsx
import { MapContainer, Marker, TileLayer, Tooltip } from "react-leaflet"
import "leaflet/dist/leaflet.css"
import "leaflet-defaulticon-compatibility"
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css"
export default function MyMap(props: any) {
const { position, zoom } = props
return <MapContainer center={position} zoom={zoom} scrollWheelZoom={false}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
}
2. Dynamically import your Component
Next, you’ll need to import your component into your page dynamically. This would eliminate the need to perform Server-Side Rendering (SSR), thereby walking around the compatibility issues that LeafletJS has with SSR.
export default function MyPage() {
const Map = useMemo(() => dynamic(
() => import('@/components/Map'),
{
loading: () => <p>A map is loading</p>,
ssr: false
}
), [])
return <div>
<Map />
</div>
}There we have it!
If you found this article helpful, do clap, share and subscribe!

Tomisin Abiodun
Senior Software Engineer @ Checkout.com
Subscribe
I bridge code and product strategy to build scalable, human-centric products with strong AI, design, frontend, and cloud expertise.