Skip to main content
Version: v3.x

Map creation and interactions

MapContainer

The MapContainer component is responsible for creating the Leaflet Map instance and providing it to its child components, using a React Context.

When creating a MapContainer element, its props are used as options to create the Map instance.

The following additional props are supported:

PropType
boundsLatLngBoundsExpression
boundsOptionsFitBoundsOptions
childrenReactNode
classNamestring
idstring
placeholderReactNode
styleCSSProperties
whenCreated(map: Leaflet.Map) => void
whenReady() => void

Except for its children, MapContainer props are immutable: changing them after they have been set a first time will have no effect on the Map instance or its container.\ The Leaflet Map instance created by the MapContainer element can be accessed by child components using one of the provided hooks or the MapConsumer component.

Hooks

useMap

Hook providing the Leaflet Map instance in any descendant of a MapContainer.

function MyComponent() {
const map = useMap();
console.log("map center:", map.getCenter());
return null;
}

function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>
);
}

useMapEvents

Hook attaching the provided LeafletEventHandlerFnMap event handlers to the map instance and returning the instance in any descendant of a MapContainer.

function MyComponent() {
const map = useMapEvents({
click: () => {
map.locate();
},
locationfound: (location) => {
console.log("location found:", location);
},
});
return null;
}

function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>
);
}

useMapEvent

Hook attaching a single event handler to the map instance and returning the instance in any descendant of a MapContainer.

function MyComponent() {
const map = useMapEvent("click", () => {
map.setView([50.5, 30.5], map.getZoom());
});
return null;
}

function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>
);
}

MapConsumer

Component using the render prop technique to provide the Leaflet Map instance in any descendant of a MapContainer.

function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MapConsumer>
{(map) => {
console.log("map center:", map.getCenter());
return null;
}}
</MapConsumer>
</MapContainer>
);
}