Skip to main content
Version: v5.x (next)

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
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.

import { MapContainer } from 'https://cdn.esm.sh/react-leaflet/MapContainer'

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>
)
}
import { useMap } from 'https://cdn.esm.sh/react-leaflet/hooks'

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>
)
}
import { useMapEvents } from 'https://cdn.esm.sh/react-leaflet/hooks'

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>
)
}
import { useMapEvent } from 'https://cdn.esm.sh/react-leaflet/hooks'