CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-leaflet

React components for Leaflet maps

Overview
Eval results
Files

React Leaflet

React components for Leaflet maps using React's declarative component model with full TypeScript support.

Package Information

PropertyValue
Packagereact-leaflet
Version5.0.0
Typenpm
LanguageTypeScript
Installationnpm install react-leaflet leaflet
Peer Dependenciesleaflet ^1.9.0, react ^19.0.0, react-dom ^19.0.0
Bundle Size~15KB minified + gzipped

Quick Start

import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";

function MyMap() {
  return (
    <MapContainer center={[51.505, -0.09]} zoom={13} style={{ height: "400px" }}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; OpenStreetMap contributors'
      />
      <Marker position={[51.505, -0.09]}>
        <Popup>A sample popup</Popup>
      </Marker>
    </MapContainer>
  );
}

📖 See Quick Start Guide for detailed setup instructions

Core Concepts

Architecture

  • MapContainer: Creates Leaflet Map instance, provides React context
  • Child Components: Access map via context, add themselves as layers
  • Declarative API: Components auto-add/remove based on React lifecycle
  • Immutable Props: Most MapContainer props only used at initialization
  • Event Handling: Via eventHandlers prop or custom hooks

Component Hierarchy

MapContainer (required root)
├── TileLayer (base map)
├── Markers & Popups (point features)
├── Vector Shapes (circles, polygons, lines)
├── Layer Groups (organize layers)
├── Controls (UI elements)
└── Media Overlays (images, video, SVG)

Component Quick Reference

Core Components

ComponentPurposeKey Props
MapContainerRoot map containercenter, zoom, style
TileLayerBase map tilesurl, attribution
MarkerPoint markerposition, icon
PopupInfo popupchildren, position
TooltipHover tooltipchildren, permanent

📚 Complete API Reference

Hooks

HookPurpose
useMap()Access map instance
useMapEvent(type, handler)Single event handler
useMapEvents(handlers)Multiple event handlers

📚 Hooks Reference

Vector Shapes

ComponentDescriptionRadius Unit
CircleCircle with geographic radiusMeters
CircleMarkerCircle with pixel radiusPixels
PolylineMulti-segment line-
PolygonFilled polygon-
RectangleRectangle from bounds-

📚 Vector Shapes Reference

Controls

ComponentPurpose
LayersControlSwitch between layers
ZoomControlZoom buttons
ScaleControlMap scale display
AttributionControlAttribution text

📚 Controls Reference

Common Imports

// Core components
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";

// Hooks
import { useMap, useMapEvent, useMapEvents } from "react-leaflet";

// Vector shapes
import { Circle, CircleMarker, Polyline, Polygon, Rectangle } from "react-leaflet";

// Layer groups
import { LayerGroup, FeatureGroup, GeoJSON, Pane } from "react-leaflet";

// Controls
import { LayersControl, ZoomControl, ScaleControl, AttributionControl } from "react-leaflet";

// Media overlays
import { ImageOverlay, SVGOverlay, VideoOverlay } from "react-leaflet";

// Core APIs (advanced)
import { useLeafletContext, createLayerComponent } from "@react-leaflet/core";

Common Types

// Position types
type LatLngExpression = 
  | LatLng 
  | [number, number] 
  | { lat: number; lng: number };

type LatLngBoundsExpression = 
  | LatLngBounds 
  | [LatLngExpression, LatLngExpression];

// Control position
type ControlPosition = 'topleft' | 'topright' | 'bottomleft' | 'bottomright';

// Path styling
interface PathOptions {
  stroke?: boolean;
  color?: string;
  weight?: number;
  opacity?: number;
  fill?: boolean;
  fillColor?: string;
  fillOpacity?: number;
}

Essential Setup

1. Install Dependencies

npm install react-leaflet leaflet
npm install -D @types/leaflet  # TypeScript

2. Import Leaflet CSS

import "leaflet/dist/leaflet.css";

3. Fix Default Marker Icons (Webpack/Vite)

import L from "leaflet";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

let DefaultIcon = L.icon({
  iconUrl: icon,
  shadowUrl: iconShadow,
});
L.Marker.prototype.options.icon = DefaultIcon;

4. Set Map Container Height

<MapContainer style={{ height: "400px", width: "100%" }}>

Key Patterns

Dynamic Map Updates

function ChangeView({ center, zoom }) {
  const map = useMap();
  map.setView(center, zoom);
  return null;
}

<MapContainer center={center} zoom={zoom}>
  <ChangeView center={center} zoom={zoom} />
  <TileLayer url="..." />
</MapContainer>

Accessing Map Instance

const mapRef = useRef<Map | null>(null);

<MapContainer ref={mapRef} center={[51.505, -0.09]} zoom={13}>
  {/* ... */}
</MapContainer>

Event Handling

function MapEvents() {
  useMapEvents({
    click: (e) => console.log('Clicked at:', e.latlng),
    zoomend: () => console.log('Zoom changed'),
  });
  return null;
}

Important Notes

⚠️ MapContainer props are immutable - Use refs/hooks for dynamic updates
⚠️ Leaflet CSS required - Must import leaflet/dist/leaflet.css
⚠️ Components must be inside MapContainer - To access map context
⚠️ Coordinate order - Leaflet uses [lat, lng], GeoJSON uses [lng, lat]
⚠️ SSR - Use dynamic imports for Next.js/server-side rendering
⚠️ Performance - Use preferCanvas={true} for many vector shapes

Documentation Structure

📖 Guides

  • Quick Start Guide - Complete setup walkthrough
  • Step-by-step tutorials for common tasks

💡 Examples

📚 Reference

Quick Troubleshooting

IssueSolution
Map not displayingImport Leaflet CSS, set explicit height
Markers not appearingFix default icon paths (see setup)
Events not firingEnsure interactive={true}, check event handlers
Performance issuesUse preferCanvas={true}, implement clustering
TypeScript errorsInstall @types/leaflet
SSR errorsUse dynamic imports, disable SSR for MapContainer

Version Compatibility

  • React Leaflet 5.x requires React 19.x and Leaflet 1.9.x
  • For React 18.x or earlier, use React Leaflet 4.x
  • Check migration guide for upgrades

Resources

Component Selection Guide

Choose Circle vs CircleMarker:

  • Use Circle for real-world distance (meters)
  • Use CircleMarker for constant pixel size

Choose LayerGroup vs FeatureGroup:

  • Use LayerGroup for simple grouping
  • Use FeatureGroup for shared styling/popups

Choose TileLayer vs ImageOverlay:

  • Use TileLayer for pannable base maps
  • Use ImageOverlay for static images over bounds

Choose Marker vs CircleMarker:

  • Use Marker for labeled points with icons
  • Use CircleMarker for data visualization dots

Install with Tessl CLI

npx tessl i tessl/npm-react-leaflet
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/react-leaflet@5.0.x