Introduction
Core concepts
React-Leaflet uses ⚛️ React's lifecycle methods to call the relevant Leaflet handlers, which has a few consequences:
DOM rendering
React does not render Leaflet layers to the DOM, this rendering is done by Leaflet itself.
React only renders the map container for the Map component and potentially empty <div>
elements for components having multiple children.
Component properties
The properties passed to the components are used to create the relevant Leaflet instance when the component will mount. When adding a component, all these properties should be supported as they are by Leaflet, however they will not be updated in the UI when they change unless they are referenced in the documentation as dynamic, which are the ones handled by the components to call the relevant Leaflet method to update it.
Dynamic properties changes are compared by reference, except for properties documenting how their changes are compared in other ways.
Component context
React-Leaflet v2 uses ⚛️ React's context API to make Leaflet elements available to other element that need it.
If you create custom components, make sure to learn about React's context and how it is used by React-Leaflet.
Lifecycle process
- The top-level
Map
renders an empty<div>
to contain the map. - The
Map
'scomponentDidMount()
handler instantiates aLeaflet.Map()
for the created<div>
with the component properties and sets this instance in state. This instance is made available in the context. - The
Map
'srender()
handler is executed again, this time rendering its children components. - When each child component is instantiated, its
constructor()
uses the Leaflet API to create the appropriate Leaflet element using the properties passed to the component. - The
render()
handler for each child is called, either returningnull
or rendering its own children. - The
componentDidMount()
handler for each child is called. This is usually when the component's Leaflet element is added to map, usually viamap.addLayer(...)
orleafletElement.addTo(...)
. - When the
componentDidUpdate()
handler of a component is called, it updates its Leaflet instance according to its supported dynamic properties. - When the
componentWillUnmount()
handler of a component is called, it removes its layer from the map if relevant.
Limitations
- Leaflet makes direct calls to the DOM when it is loaded, therefore this library is not compatible with server-side rendering.
- The components exposed are abstractions for Leaflet layers, not DOM elements. Some of them have properties that can be updated directly by calling the setters exposed by Leaflet while others should be completely replaced, by setting an unique value on their
key
property so that they are properly handled by React's algorithm.