React-Leaflet uses ⚛️ React's lifecycle methods to call the relevant Leaflet handlers, which has a few consequences:
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.
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.
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.
- The top-level
Maprenders an empty
<div>to contain the map.
componentDidMount()handler instantiates a
Leaflet.Map()for the created
<div>with the component properties and sets this instance in state. This instance is made available in the context.
render()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.
render()handler for each child is called, either returning
nullor rendering its own children.
componentDidMount()handler for each child is called. This is usually when the component's Leaflet element is added to map, usually via
- 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.
- 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
keyproperty so that they are properly handled by React's algorithm.